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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With