Search code examples
rpipetidyversemagrittr

R: Using pipe %>% and pkg::fo leads to error "Error in .::base : unused argument"


I am using magrittr's pipe %>%, followed immediately by a function called by: package::function, and get the error: Error in .::base : unused argument (mean)

What is the problem?

library(magrittr)
c(1,2) %>%
  base::mean
#> Error in .::base: unused argument (mean)

Solution

  • What's happening is that magrittr is getting confused as to exactly what function you want to insert the previous value into. When you do just

    c(1,2) %>%
      mean
    

    magrittr is able to easily see that mean is a symbol that points to the mean function. But when you do base::mean, things get a bit trickier because :: is also a function in R. Let's compare the difference between base::mean and base::mean() in R in terms of how they are translated into function calls.

    as.list(quote(base::mean))
    # [[1]]
    # `::`    
    # [[2]]
    # base    
    # [[3]]
    # mean
    
    as.list(quote(base::mean()))
    #  [[1]]
    # base::mean
    

    You can see these parse differently. When you just type base::mean R will see the :: function first and will try to pass in the numbers there. Basically to's trying to call

    `::`(., base, mean)
    

    which doesn't make sense can that's what gives you that specific error message

    But if you explicitly add the (), R can see that you are trying to call the function returned from base::mean so it will add the parameter to the right place. So you can do

    c(1,2) %>%
      base::mean()
    

    or

    c(1,2) %>%
        (base::mean)