dplyr 中的链算术运算符与 %>% 管道 [英] Chain arithmetic operators in dplyr with %>% pipe

查看:24
本文介绍了dplyr 中的链算术运算符与 %>% 管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解为什么在 dplyrmagrittr 包中,更具体地说,链接函数 %>% 有基本运算符 +-*/

I would like to understand why, in the the dplyr or magrittr package, and more specifically the chaining function %>% has some trouble with the basic operators +, -, *, and /

链接获取前一条语句的输出并将其作为下一条语句的第一个参数:

Chaining takes the output of previous statement and feeds it as first argument of the next:

1:10 %>% sum
# [55]

为什么这不起作用

1:10 %>%  *2 %>% sum
1:10 %>% .*2 %>% sum

我还发现以下语法适用于加法/减法,但不适用于乘法或除法.为什么会这样?

I also found that the following syntax works for adding/substracting, but not multiply or divide. why so?

1:10 %>% +(2) # works OK
1:10 %>% *(2) # nope...

那么我是否应该编写一个匿名函数来对我的 data.frame 执行 *2 操作?

So should I write an anonymous function even to do a *2 operation on my data.frame?

1:10 %>% (function(x) x*2) %>% sum

谢谢,我在其他 SO 问题中找不到答案.

Thanks, I couldn't find the answer in other SO questions.

推荐答案

用反引号或引号将运算符括起来,事情应该按预期工作:

Surround the operators with backticks or quotes, and things should work as expected:

1:10 %>%  `*`(2) %>% sum
# [1] 110

1:10 %>%  `/`(2) %>% sum
# [1] 27.5

这篇关于dplyr 中的链算术运算符与 %>% 管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆