我正在尝试按在函数的先前步骤中动态生成的列进行分组。该列将有一个模式(后缀)。我可以使用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()
.
最佳答案
虽然我经常在 mutate
和 summarise
内部的赋值中使用这种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/