-1

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
Ian
  • 123
  • 5

3 Answers3

1

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
user438383
  • 5,716
  • 8
  • 28
  • 43
1

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
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

You can use the function form of ^ operator:

library(magrittr)

1:5 %>% `^`(-1)
[1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000