gpt4 book ai didi

r - 将 enquo 与 infer 包一起使用

转载 作者:行者123 更新时间:2023-12-04 10:50:45 25 4
gpt4 key购买 nike

我正在使用 infer 包运行卡方测试,例如,

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)

或者另一种选择是利用 enexprexpr来自 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

关于r - 将 enquo 与 infer 包一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59481546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com