我正在尝试将用户输入解析为函数调用的参数(在表达式中)。好像我很接近但是!将我的论点用括号括起来,这是行不通的。我正在尝试使用用户输入重新创建以下内容:
recipe(mpg ~ cyl + hp + wt + disp, data = mtcars) %>%
step_log(disp, base = 10, offset = 0) %>%
prep()
library(rlang)
library(tidymodels)
user_dv <- "mpg"
user_idv <- c("cyl", "hp", "wt", "disp")
user_step <- "log"
user_selector <- "disp"
user_args <- "base = 10, offset = 0"
formula <- as.formula(paste(user_dv, paste(user_idv, collapse = " + "), sep = " ~ "))
rcp <- expr(recipe(!!formula,data = mtcars))
add_step <- function(x, step, selector, args){
f <- parse_expr(paste0("step_", step))
vars <- ensym(user_selector)
args <- args %>%
str_replace(",", ";") %>%
parse_exprs()
step_expr <- call2(f, vars, !!!args)
expr(!!x %>% !!step_expr)
}
rcp %>%
add_step(user_step, user_selector, user_args) %>%
eval() %>%
prep()
我的表情最终看起来像这样:
recipe(mpg ~ cyl + hp + wt + disp, data = mtcars) %>%
step_log(disp, (base = 10), (offset = 0))
哪个不准备()