r - Tidy Eval,使用 enquo 和 infer 包
问题描述
这是我在这个网站上的第一个问题。
我尝试使用的推断包是 tidyverse (tidymodels)链接的一部分
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 并且一切看起来都很好,所以我不明白这个错误。
解决方案
问题在于公式。我们可以paste
在将quosure转换为字符串( 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)
推荐阅读
- ruby-on-rails - Activerecord 查询比原始 sql 花费更多时间
- javascript - 我想将 HTML 表转换为角度 2 的 JSON 数组
- forms - 具有必填字段的 MVC 表单作为下拉列表或创建新值
- sql - GROUP BY 与 SUM 不删除空(null)值
- wordpress - Wordpress 中缺少随机图标
- graph - 如何在散景中为networkx图添加边缘标签(交互式或永久标签)?
- leaflet - 网络地图应用程序。地理服务器的使用:是还是不是?
- mongodb - 是否有可能在 MongoDB 中获得滞后值?
- r - 时间序列处理中的不适用?
- android - 拍照并保存到内部存储并获取 getUriForFile 错误