链接中的算术运算符 [英] Chaining arithmetic operators in dplyr

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

问题描述

我想了解为什么在 dplyr magrittr 包中,更具体地说,链接功能%>%在基本运算符 + - * /



获取以前语句的输出,并将其作为下一个语句的第一个参数提交:

  1:10%>%sum 
#[55]

因此,这是不行的

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

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

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

所以我应该写一个匿名的功能,一个 * 2 对我的data.frame的操作

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

在其他SO问题中找不到答案。

解决方案

使用反引号或引号围绕运算符,事情应按预期工作:

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

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

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]

Thus how come this doesn't work

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...

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

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

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

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

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