我们可以将字符串对象传递到
.var
. 所以把问题转化为
quo_name
用这个
tryfn <- function(data, x, y) {
# creating a dataframe (works)
x <- enquo(x)
y <- enquo(y)
x1 <- quo_name(x)
y1 <- quo_name(y)
data <-
dplyr::select(
.data = data,
!!x,
!!y
)
print(head(data))
fml <- formula(paste0(y1, " ~ ", x1))
# convert the grouping variable to factor (doesn't work)
data <- data %>%
stats::na.omit(.) %>%
dplyr::mutate_at(
.var = x1,
.funs = ~base::droplevels(x = base::as.factor(x = .x))
)
bartlett <- stats::bartlett.test(
formula = fml,
data = data,
na.action = na.omit
)
bartlett
}
-试验
# using the function
out <- tryfn(
data = mtcars,
x = am,
y = wt
)
out
# Bartlett test of homogeneity of variances
#data: wt by am
#Bartlett's K-squared = 0.71483, df = 1, p-value = 0.3978