如何在 R 中的自定义函数中的管道中传递动态列名称

sea*_*ele 7 r dplyr custom-function

我已经基于此线程使用 dplyr::mutate() 创建了一个动态列名称在 `dplyr` 中使用动态变量名称,现在我想对新列进行排序....但我没有正确传递该列姓名

library(glue)
library(dplyr)

# data
set.seed(123)
df <- data.frame(distance = sample(1:100, size = 10))

# custom function
multiply_function <- function(df, metric, multiplier){
  
  df %>% 
    mutate(., "{{metric}}_x{{multiplier}}" := {{metric}} * multiplier) %>% 
    arrange(desc("{{metric}}_x{{multiplier}}")) # <--- this is not working
}

df %>% 
  multiply_function(., metric = distance, multiplier = 3)

   distance distance_x3
1        31          93
2        79         237
3        51         153
4        14          42
5        67         201
6        42         126
7        50         150
8        43         129
9        97         291
10       25          75
Run Code Online (Sandbox Code Playgroud)

MrF*_*ick 5

不幸的是,我不知道是否有任何方法可以将这种漂亮的粘合语法与不在 .a 左侧的任何内容一起使用:=。魔法就在那里发生了。如果您处理显式转换以对自己求和并手动构建字符串,那么您可以得到一些东西。这不漂亮,但是可行

multiply_function <- function(df, metric, multiplier){
  metric <- ensym(metric)
  newname <- glue::glue("{rlang::as_string(metric)}_x{as.character(multiplier)}")
  df %>% 
    mutate("{newname}" := !!metric * multiplier) %>% 
    arrange(desc(.data[[newname]]))
}
Run Code Online (Sandbox Code Playgroud)