我知道在函数内部使用lazyeval来使用dplyr引用列名,但我被卡住了。一般来说,当创建一个使用dplyr的函数时,该函数还从函数参数中引用列名,实现这一目标的最惯用方法是什么?谢谢。
library(lazyeval)
## Create data frame
df0 <- data.frame(x=rnorm(100), y=runif(100))
##########################################
## Sample mean; this way works
##########################################
df0 %>%
filter(!is.na(x)) %>%
summarize(mean=mean(x))
##########################################
## Sample mean via function; does not work
##########################################
dfSummary2 <- function(df, var_y) {
p <- df %>%
filter(!is.na(as.name(var_y))) %>%
summarize(mean=mean(as.name(var_y)))
return(p)
}
dfSummary(df0, "x")
# mean
# 1 NA
# Warning message:
# In mean.default("x") : argument is not numeric or logical: returning NA
##########################################
## Sample mean via function; also does not work
##########################################
dfSummary <- function(df, var_y) {
p <- df %>%
filter(!is.na(var_y)) %>%
summarize(mean=mean(var_y))
return(p)
}
dfSummary(df0, "x")
# mean
# 1 NA
# Warning message:
# In mean.default("x") : argument is not numeric or logical: returning NA