Search code examples
rpurrrmagrittr

Why doesn't purrr::transpose work with the pipe operator?


I don't understand why purrr::transpose issues an error after the pipe operator.
This isn"t the case with other functions like purrr::map.

See example below:

library(purrr)
# Works
identical(mtcars %>% map(~{.x}), mtcars %>% purrr::map(~{.x}))
# [1] TRUE

# Works
mtcars %>% transpose

# Doesn't work
mtcars %>% purrr::transpose
#Error in .::purrr : unused argument (transpose)

Solution

  • It is possible I have misunderstood the namespace operator please correct me if so however this is what I believe the reason to be.

    I believe this is an issue where the namespace notation actually acts as an infix operator ::. This means that the function call it is trying to use is:

    `::`(mtcars, purrr, transpose)
    
    

    The error here occurs as the namespace infix operator can only accept two arguments: the package name and the function from the package.

    This isn't expected by the user as we would want to be able to use functions from external namespaces with the pipe operator. This is because the code is confused as to what the function attempting to be called is and so it finds the first function it can (in this case ::).

    The solution to this is to use brackets to note that transpose is the function or that purrr::transpose should be evaluated first. We can do this with the following code:

    # purrr::transpose is the function
    mtcars %>% purrr::transpose()
    
    # Evaluate this block as the expression of the function
    mtcars %>% (purrr::transpose)