问题
Is it possible to use piping from the dplyr package to do numeric calculations? A simple example is:
0.15 %>% 3.8416 * (.*(1-.))/(0.03^2) #does not work
seq(1,10,1) %>% log(.) %>% .^2 #works
Tying to understand more of how piping works and when it can and cannot be used. I really enjoy using the piping feature and want to find a way to use it for these types of numeric calculations.
Many thanks
回答1:
You have an operator precedence problem. It's trying to start by doing
0.15 %>% 3.8416
which doesn't make sense. You need to group all your calculations in a code block
0.15 %>% {3.8416 * (.*(1-.))/(0.03^2)}
回答2:
All of these are equivalent, you'll need magrittr
for the first one, dplyr
is enough for the next 2:
library(magrittr)
0.15 %>% multiply_by(subtract(1,.)) %>% multiply_by(3.8416) %>% divide_by(0.03^2)
0.15 %>% `*`(`-`(1,.)) %>% `*`(3.8416) %>% `/`(0.03^2)
0.15 %>% {3.8416 * (.*(1-.))/(0.03^2)}
来源:https://stackoverflow.com/questions/46836185/numeric-calculations-using-dplyr-piping-commands