r - 按动态生成的列进行分组,模式为 `dplyr`

标签 r dplyr tidyeval

我正在尝试按在函数的先前步骤中动态生成的列进行分组。该列将有一个模式(后缀)。我可以使用dplyr::contains() ,但这不是最准确的方法,因为我只有一列,如果将来出现其他带有后缀的列,可能会产生严重的错误。

fun <- function(df, target){
  # previous steps generate a dynamic columns
  # dynamic columns have suffixes
  # let's assume I only care about Length
  df %>% 
    group_by("{target}.Length")
  # do more stuff
}

我正在使用dplyr == 1.0.8并认为我这种事情得到了支持。我可能错过了一些非常简单的东西,并且 "Petal"无法正确粘贴并解释为正确的列名称。我尝试了 {} 的几种组合和{{}}它没有像我预期的那样工作。例如:

> fun(iris, "Petal") %>% head()
# A tibble: 6 × 6
# Groups:   "{target}.Length" [1]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species `"{target}.Length"`
         <dbl>       <dbl>        <dbl>       <dbl> <fct>   <chr>              
1          5.1         3.5          1.4         0.2 setosa  {target}.Length    
2          4.9         3            1.4         0.2 setosa  {target}.Length    
3          4.7         3.2          1.3         0.2 setosa  {target}.Length    
4          4.6         3.1          1.5         0.2 setosa  {target}.Length    
5          5           3.6          1.4         0.2 setosa  {target}.Length    
6          5.4         3.9          1.7         0.4 setosa  {target}.Length 

我对 mutate() 使用相同类型的符号成功,但不适用于 group_by() .

最佳答案

虽然我经常在 mutatesummarise 内部的赋值中使用这种glue模式,但我还没有看到任何使用它的例子在其他 dplyr 动词中。然而,一种选择是使用 .data 代词和 paste0,这不是那么优雅,但有效:

library(dplyr, warn=FALSE)

fun <- function(df, target){
  df %>% 
    group_by(.data[[paste0(target, ".Length")]])
}

fun(iris, "Petal") %>% head()
#> # A tibble: 6 × 5
#> # Groups:   Petal.Length [4]
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>          <dbl>       <dbl>        <dbl>       <dbl> <fct>  
#> 1          5.1         3.5          1.4         0.2 setosa 
#> 2          4.9         3            1.4         0.2 setosa 
#> 3          4.7         3.2          1.3         0.2 setosa 
#> 4          4.6         3.1          1.5         0.2 setosa 
#> 5          5           3.6          1.4         0.2 setosa 
#> 6          5.4         3.9          1.7         0.4 setosa

关于r - 按动态生成的列进行分组,模式为 `dplyr`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73966509/

相关文章:

r - 在R中的数据表的列中删除一个单词

r - 将 ggplot2 aes_string 与箱线图一起使用的问题

r - 在 group_by 中,改变一个新列,根据列的出现顺序获取列的值

r - 如何以简洁的方式将表达式传递给 filter() 动词?

r - 使用 `dplyr::mutate()` 从向量中指定的名称创建几个新变量

r - 通过 R 中的函数传递字符串

R:具有特定因子水平的所有案例的平均值

r - 在 R 中更改变量名称包含特定模式的值

r - 使用 dplyr::lag 整理数据框并填充变量

r - 如何将函数中新创建的变量引用到辅助函数?