Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the pipe in unique() function in r is not working

I have some troubles using the pipe operator (%>%) with the unique function.

df = data.frame(
  a = c(1,2,3,1),
  b = 'a')

unique(df$a) # no problem here
df %>% unique(.$a) # not working here
# I got "Error: argument 'incomparables != FALSE' is not used (yet)"

Any idea?

like image 224
Rtist Avatar asked Mar 21 '18 13:03

Rtist


2 Answers

What is happening is that %>% takes the object on the left hand side and feeds it into the first argument of the function by default, and then will feed in other arguments as provided. Here is an example:

df = data.frame(
  a = c(1,2,3,1),
  b = 'a')

MyFun<-function(x,y=FALSE){
  return(match.call())
}
> df %>% MyFun(.$a)
MyFun(x = ., y = .$a)

What is happening is that %>% is matching df to x and .$a to y.

So for unique your code is being interpreted as:

unique(x=df, incomparables=.$a)

which explains the error. For your case you need to pull out a before you run unique. If you want to keep with %>% you can use df %>% .$a %>% unique() but obviously there are lots of other ways to do that.

like image 186
John Paul Avatar answered Sep 22 '22 02:09

John Paul


As other answers mention : df %>% unique(.$a) is equivalent to df %>% unique(.,.$a).

To force the dots to be explicit you can do:

df %>% {unique(.$a)}
# [1] 1 2 3

An alternative option from magrittr

df %$% unique(a)
# [1] 1 2 3

Or possibly stating the obvious:

df$a %>% unique
# [1] 1 2 3
like image 26
Moody_Mudskipper Avatar answered Sep 23 '22 02:09

Moody_Mudskipper