When using dplyr, is there a function such that:
Reciprocal <- 1:5 %>%
reciprocalfunction()
Reciprocal
the desired result being:
[1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000
dplyr
normally works on dataframes but it's simple enough to do
data.frame(a = 1:5) %>% mutate(a = 1/a)
a
1 1.0000000
2 0.5000000
3 0.3333333
4 0.2500000
5 0.2000000
Or just define a custom function:
r_p = function(x) 1 / x
1:5 %>% r_p
[1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000
The pipe symbol %>%
originated in the magrittr package, which has the function divide_by
to avoid having to define your own division operator for use in the pipe.
library(magrittr)
1:5 %>% divide_by(1, .)
#> [1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000
You can use the function form of ^
operator:
library(magrittr)
1:5 %>% `^`(-1)
[1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000