,可以使用以下方式:
library(dplyr)
data <- data.frame(col1 = c(1, 2, 3), col2 = c(4, 5, 6))
col_name <- quo(col1)
result <- data %>% summarize(avg = mean(!!col_name))
在上述代码中,quo(col1)将列名"col1"转换为一个引用对象,然后使用!!来解引用该对象,从而在mean()函数中访问该列。
library(dplyr)
data <- data.frame(col1 = c(1, 2, 3), col2 = c(4, 5, 6))
col_names <- c("col1", "col2")
result <- data %>% summarize_all(~mean(!!enquo(.)))
在上述代码中,enquo(.)将列名转换为引用对象,并直接在mean()函数中使用引用对象。使用~表示对每个列名应用相同的函数。
总结:在summarize_all dplyr结构内部使用的函数中访问列名,可以使用quo()函数将列名转换为引用对象,并使用!!来解引用该对象;也可以使用enquo()函数将列名转换为引用对象,并直接在函数中使用引用对象。
领取专属 10元无门槛券
手把手带您无忧上云