在单个 mutate() 语句中组合多个 across(),同时控制 R 中的变量名称

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

我有以下数据框:

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

   a  b a_sd b_sd
1 10 20    2    3

我想计算 a/a_sd、b/b_sd,并将结果添加到数据框,并将它们命名为 ratio_a、ratio_b。在我的数据框中,我有很多变量,所以我需要一个 'wide' 解决方案。我试过了:

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

这给了:

  a        b a_sd b_sd
1 5 6.666667    2    3

所以这行得通,但新值取代了旧值。如何将结果添加到数据框并控制新名称?

您可以在 across

中使用 .names 参数
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