我正在使用推断包来运行卡方检验,例如,
df %>%
chisq_test(label ~ feature)
我想将其放入函数中,所以我可以写:
my_chisq_function(df, label, feature)
我通常会通过编写与此类似的函数来做到这一点:
my_chisq_function = function(df, label, feature) {
feature = enquo(feature)
label = enquo(label)
df %>%
chisq_test(!!label ~ !!feature)
}
但是当我运行它时:
my_chisq_function(df, cohort, gender)
我收到一个错误:
Error: The response variable `!` cannot be found in this dataframe.The response variable `!label` cannot be found in this dataframe.
关于如何使它起作用的任何想法/建议?
谢谢,D
我们可以在转换为字符串后构造一个公式
my_chisq_function <- function(df, label, feature) {
feature <- rlang::as_string(rlang::ensym(feature))
label <- rlang::as_string(rlang::ensym(label))
df %>%
infer::chisq_test(as.formula(stringr::str_c(label, feature, sep="~ ")))
}
my_chisq_function(df, cohort, gender)
或者另一个选择是将enexpr
与expr
中的rlang
结合使用
my_chisq_function <- function(df, label, feature) {
df %>%
infer::chisq_test(rlang::expr(!! rlang::enexpr(label) ~
!! rlang::enexpr(feature)))
}
-测试
df1 <- mtcars
df1$carb <- as.factor(df1$carb)
df1$gear <- as.factor(df1$gear)
my_chisq_function(df1, carb, gear)
# A tibble: 1 x 3
# statistic chisq_df p_value
# <dbl> <int> <dbl>
#1 16.5 10 0.0857
[C0的替代项
substitute