4

I have the following dataframe:

df = data.frame(a = 10, b = 20, a_sd = 2, b_sd = 3)

   a  b a_sd b_sd
1 10 20    2    3

I want to compute a/a_sd, b/b_sd, and to add the results to the dataframe, and name them ratio_a, ratio_b. In my dataframe I have a lot of variables so I need a 'wide' solution. I tried:

df %>% 
  mutate( across(one_of( c('a','b')))/across(ends_with('_sd'))) 

This gave:

  a        b a_sd b_sd
1 5 6.666667    2    3

So this worked but the new values took the place of the old ones. How can I add the results to the data frame and to control the new names?

Ric S
  • 9,073
  • 3
  • 25
  • 51
Rtist
  • 3,825
  • 2
  • 31
  • 40

1 Answers1

6

You can use the .names argument inside across

df %>% 
  mutate(across(one_of(c('a','b')), .names = 'ratio_{col}')/across(ends_with('_sd'))) 
#    a  b a_sd b_sd ratio_a  ratio_b
# 1 10 20    2    3       5 6.666667
Ric S
  • 9,073
  • 3
  • 25
  • 51
  • Why did you specify the .names argument in the first across() and not in the second one? – Rtist Nov 26 '20 at 13:44
  • Honestly, I don't know how dplyr operates internally, but it is more intuitive to put it in the first `across`. In fact, the code doesn't return the desired output if you put it in the second `across` – Ric S Nov 26 '20 at 13:46