Search code examples
rtidyversedplyracross

Combining multiple across() in a single mutate() sentence, while controlling the variables names in R


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?


Solution

  • 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