Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 699
Matifou Avatar asked Mar 04 '19 21:03

Matifou


People also ask

What does the error unused argument mean in R?

The “unused argument error in r” message is caused by a mistake in the code when entering an argument or object such as a data frame, vector, or matrix into a base r function. It is not a case of missing values or data but rather a variable that is not expected as an additional argument.

Why is %>% not found?

Error in R – could not find function “%>%” – means that you don't have loaded or installed the R package that is using that. The same is with any other “could not find function” R error. One of the most popular R packages that are using %>% or pipe operator is dplyr.


2 Answers

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)
like image 122
MrFlick Avatar answered Sep 22 '22 17:09

MrFlick


Note that there is a version of magrittr that does not have this issue but it hasn't been pushed to CRAN for a very long time now.

As documented in this issue, github version of magrittr pipes can successfully deal with

c(1,2) %>%
    base::mean
[1] 1.5

This was fixed 4 years ago but never made it to CRAN. Since most people would be using the CRAN version, I would not suggest writing code that depends on this fix.

like image 26
OganM Avatar answered Sep 19 '22 17:09

OganM