Numeric calculations using dplyr piping commands

时光总嘲笑我的痴心妄想 提交于 2019-12-13 20:22:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!