将公式作为参数传递很简单,我不建议对此进行整洁的评估。我将按如下方式执行此操作(仅对新列名使用一点 tidyeval):
library(tidyverse)
add_predictions <- function(.data, formula,
.fun = lm, col = pred) {
col <- enquo(col)
col <- quo_name(col)
mod <- .fun(formula = formula, data = .data)
mutate(.data, !! col := predict(mod))
}
cars %>%
add_predictions(speed ~ dist, col = speed_pred)
# speed dist speed_pred
# 1 4 2 8.615041
# 2 4 10 9.939581
# 3 7 4 8.946176
# 4 7 22 11.926392
# 5 8 16 10.932987
# 6 9 10 9.939581
# 7 10 18 11.264122
# 8 10 26 12.588663
# 9 10 34 13.913203
# 10 11 17 11.098554
# ...
现在我知道您想使用 tidy 评估作为练习。使用您想要的函数签名:
add_predictions_2 <- function(.data, model_exp, col = pred) {
col <- enquo(col)
col <- quo_name(col)
model_exp <- enquo(model_exp)
mod <- rlang::eval_tidy(model_exp, data = list(. = .data))
mutate(.data, !! col := predict(mod))
}
cars %>%
as_tibble() %>%
add_predictions_2(lm(speed ~ dist, data = .))
# # A tibble: 50 x 3
# speed dist pred
# <dbl> <dbl> <dbl>
# 1 4 2 8.62
# 2 4 10 9.94
# 3 7 4 8.95
# 4 7 22 11.9
# 5 8 16 10.9
# 6 9 10 9.94
# 7 10 18 11.3
# 8 10 26 12.6
# 9 10 34 13.9
# 10 11 17 11.1
# # ... with 40 more rows