Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

r - Chain arithmetic operators in dplyr with %>% pipe

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...