在 r 中使用 unique() 函数中的管道不起作用
Using the pipe in unique() function in r is not working
我在使用具有独特功能的管道运算符 (%>%) 时遇到了一些问题。
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)"
有什么想法吗?
发生的事情是 %>%
默认将左侧的对象送入函数的第一个参数,然后送入提供的其他参数。这是一个例子:
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)
发生的事情是 %>%
正在将 df
匹配到 x
并且将 .$a
匹配到 y
。
所以对于 unique
,您的代码被解释为:
unique(x=df, incomparables=.$a)
这解释了错误。对于您的情况,您需要在 运行 unique 之前拉出 a
。如果你想保持 %>%
你可以使用 df %>% .$a %>% unique()
但显然还有很多其他方法可以做到这一点。
如其他答案所述:df %>% unique(.$a)
等同于 df %>% unique(.,.$a)
。
要强制这些点是明确的,你可以这样做:
df %>% {unique(.$a)}
# [1] 1 2 3
magrittr
的备选方案
df %$% unique(a)
# [1] 1 2 3
或者可能陈述显而易见的:
df$a %>% unique
# [1] 1 2 3
我在使用具有独特功能的管道运算符 (%>%) 时遇到了一些问题。
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)"
有什么想法吗?
发生的事情是 %>%
默认将左侧的对象送入函数的第一个参数,然后送入提供的其他参数。这是一个例子:
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)
发生的事情是 %>%
正在将 df
匹配到 x
并且将 .$a
匹配到 y
。
所以对于 unique
,您的代码被解释为:
unique(x=df, incomparables=.$a)
这解释了错误。对于您的情况,您需要在 运行 unique 之前拉出 a
。如果你想保持 %>%
你可以使用 df %>% .$a %>% unique()
但显然还有很多其他方法可以做到这一点。
如其他答案所述:df %>% unique(.$a)
等同于 df %>% unique(.,.$a)
。
要强制这些点是明确的,你可以这样做:
df %>% {unique(.$a)}
# [1] 1 2 3
magrittr
df %$% unique(a)
# [1] 1 2 3
或者可能陈述显而易见的:
df$a %>% unique
# [1] 1 2 3