这是我在此网站上的第一个问题。
我要使用的推断包是tidyverse(tidymodels)link
的一部分library(tidyverse)
library(rlang)
library(infer)
mtcars$am <- as.factor(mtcars$am)
f <- function(dataset, col){
col <- enquo(col)
bootstrap <- dataset %>%
specify(!!col ~ am ) %>%
generate(reps = 100, type = "bootstrap") %>%
calculate("diff in means", order = c("1", "0"))
}
f(mtcars, mpg)
Error: The response variable `!` cannot be found in this dataframe.The response variable `!col` cannot be found in this dataframe.
In addition: Warning message:
In if (!(as.character(attr(x, "response")) %in% names(x))) { :
Show Traceback
Rerun with Debug
Error: The response variable `!` cannot be found in this dataframe.The response variable `!col` cannot be found in this dataframe.
我尝试使用qq_show,并且一切看起来都很好,所以我不理解该错误。
答案 0 :(得分:1)
问题出在公式中。将等量转换为字符串(paste
)并将字符串转换为quo_name
对象之后,我们可以使用formula
f <- function(dataset, col){
col <- enquo(col)
dataset %>%
specify(as.formula(paste0(quo_name(col), '~ am'))) %>%
generate(reps = 100, type = "bootstrap") %>%
calculate("diff in means", order = c("1", "0"))
}
f(mtcars, mpg)
# A tibble: 100 x 2
# replicate stat
# <int> <dbl>
# 1 1 8.41
# 2 2 10.7
# 3 3 7.65
# 4 4 7.21
# 5 5 7.47
# 6 6 6.59
# 7 7 9.32
# 8 8 5.70
# 9 9 8.25
#10 10 6.24
# ... with 90 more rows
基于@Lionel Henry的建议
f <- function(dataset, col){
col <- ensym(col)
g <- expr(!!col ~ am)
dataset %>%
specify(g) %>%
generate(reps = 100, type = "bootstrap") %>%
calculate("diff in means", order = c("1", "0"))
}
f(mtcars, mpg)