在此示例中,我有一个简单的函数,它通过...
传递变量名,并利用enquos
函数将其传递给dplyr中的enquos
运算符。
group_by
group_by
我想扩展上面的函数,除了产生的结果之外,还要创建一个新的标量字符,该标量字符将以# Libraries
library(dplyr)
library(rlang)
sample_function <- function(x, ...) {
group_vars <- enquos(...)
x %>%
group_by(!!!group_vars) %>%
summarise(num_obs = n())
}
的格式反映传递给mtcars %>% sample_function(cyl, am)
# A tibble: 6 x 3
# Groups: cyl [3]
cyl am num_obs
<dbl> <dbl> <int>
1 4 0 3
2 4 1 8
3 6 0 4
4 6 1 3
5 8 0 12
6 8 1 2
的变量的名称。
enquos
生产的字符串与所需的格式不匹配。
"var1, var2, ..."
仅返回最初通过library(dplyr)
library(rlang)
sample_function <- function(x, ...) {
group_vars <- enquos(...)
# Problem:
# Create test object of quoted variables
assign(x = "used_group_variables",
value = quo_text(group_vars),
envir = globalenv())
# Summary
x %>%
group_by(!!!group_vars) %>%
summarise(num_obs = n())
}
传递的所有变量的名称,并以“`”作为分隔符进行粘贴。
used_group_variables
# [1] "structure(list(~cyl, ~am), .Names = c(\"\", \"\"), class = c(\"quosures\", \n\"list\"))"
enquos
中的所有内容强制转换为used_group_variables
# "cyl, am"
格式的字符串。您可以使用enquos
并用"name1, name2, ..."
折叠:
sapply
输出:
toString
编辑:如@LionelHenry在评论中所建议,您可能想使用sample_function <- function(x, ...) {
group_vars <- enquos(...)
assign(x = "used_group_variables",
value = toString(sapply(group_vars, quo_name)),
envir = globalenv())
x %>%
group_by(!!!group_vars) %>%
summarise(num_obs = n())
}
而不是mtcars %>% sample_function(am, cyl)
used_group_variables
# [1] "am, cyl"
,因为后者会误导人,并且可能会被弃用。