复合函数中管道运算符的行为 purrr - dplyr
behavior of pipe operator in compostie functions purrr - dplyr
purrr-dplyr 包中管道运算符的使用(简而言之)定义如下:
y%>%f(x,.,z) is the same as f(x,y,z)
我正在尝试使用管道运算符完成以下任务。首先,我向您展示了不使用管道的任务:
#####for reproducibility
set.seed(50)
z0<-factor(sample(c(letters[1:3],NA),100,replace = T))
###the task
rep(1,length(table(z0)))
现在我想用管道来做这个:
z0%>%table%>%rep(1,length(.))
但是结果不一样。管道运算符似乎无法处理对函数组合的正确分配。即
y%>%f(x,g(.)) should be the same as f(x,g(y))
所以,具体问题是是否可以做到
y%>%f(x,g(.))
提前感谢您的意见。
%>%
实现了第一个参数规则,即如果.
不是直接参数,它将前面的数据作为第一个参数传递给函数;在你的第二种情况下,rep
的参数是 1
和 length(.)
,所以第一个参数规则生效;为避免这种情况,请使用 {}
将表达式括起来;您可以阅读更多相关信息 at Re-using the placeholder for attributes:
Re-using the placeholder for attributes
It is straight-forward to use the placeholder several times in a
right-hand side expression. However, when the placeholder only appears
in a nested expressions magrittr will still apply the first-argument
rule. The reason is that in most cases this results more clean code.
x %>% f(y = nrow(.), z = ncol(.)) is equivalent to f(x, y = nrow(x), z = ncol(x))
The behavior can be overruled by enclosing the right-hand side in
braces:
x %>% {f(y = nrow(.), z = ncol(.))} is equivalent to f(y = nrow(x), z = ncol(x))
rep(1,length(table(z0)))
# [1] 1 1 1
等价于:
z0 %>% table %>% {rep(1,length(.))}
# [1] 1 1 1
purrr-dplyr 包中管道运算符的使用(简而言之)定义如下:
y%>%f(x,.,z) is the same as f(x,y,z)
我正在尝试使用管道运算符完成以下任务。首先,我向您展示了不使用管道的任务:
#####for reproducibility
set.seed(50)
z0<-factor(sample(c(letters[1:3],NA),100,replace = T))
###the task
rep(1,length(table(z0)))
现在我想用管道来做这个:
z0%>%table%>%rep(1,length(.))
但是结果不一样。管道运算符似乎无法处理对函数组合的正确分配。即
y%>%f(x,g(.)) should be the same as f(x,g(y))
所以,具体问题是是否可以做到
y%>%f(x,g(.))
提前感谢您的意见。
%>%
实现了第一个参数规则,即如果.
不是直接参数,它将前面的数据作为第一个参数传递给函数;在你的第二种情况下,rep
的参数是 1
和 length(.)
,所以第一个参数规则生效;为避免这种情况,请使用 {}
将表达式括起来;您可以阅读更多相关信息 at Re-using the placeholder for attributes:
Re-using the placeholder for attributes
It is straight-forward to use the placeholder several times in a right-hand side expression. However, when the placeholder only appears in a nested expressions magrittr will still apply the first-argument rule. The reason is that in most cases this results more clean code.
x %>% f(y = nrow(.), z = ncol(.)) is equivalent to f(x, y = nrow(x), z = ncol(x))
The behavior can be overruled by enclosing the right-hand side in braces:
x %>% {f(y = nrow(.), z = ncol(.))} is equivalent to f(y = nrow(x), z = ncol(x))
rep(1,length(table(z0)))
# [1] 1 1 1
等价于:
z0 %>% table %>% {rep(1,length(.))}
# [1] 1 1 1