我编写了一个函数来对过滤后的数据集运行单变量回归。该函数将用于过滤的值和回归模型的预测变量名称作为参数。如您所见,我正在努力处理数据屏蔽和评估。如何在回归模型中直接使用 .pred 参数?谢谢!
pacman::p_load(tidyverse, purrr, broom)
data("mtcars")
# my function
regr_func <- function(.cyl, .pred){
mtcars %>%
filter(cyl == .cyl) %>% # cars with .cyl cylinders
mutate(x = .data[[.pred]]) %>% # this is a bit of a hack :(
lm(mpg ~ x, data = .) %>%
tidy() %>%
mutate(predictor = .pred,
cylinders = .cyl)
}
regr_func(4, "hp")
#> # A tibble: 2 × 7
#> term estimate std.error statistic p.value predictor cylinders
#> <chr> <dbl> <dbl> <dbl> <dbl> <chr> <dbl>
#> 1 (Intercept) 36.0 5.20 6.92 0.0000693 hp 4
#> 2 x -0.113 0.0612 -1.84 0.0984 hp 4
Created on 2021-10-26 by the reprex package (v2.0.1)
更新
感谢 Jon 的提示,我可以重写该函数以将 .pred 参数直接传递给 lm(),但现在我无法将数据通过管道传输到 lm(),因此我必须在功能。
regr_func1 <- function(.cyl, .pred){
tmp <- mtcars %>% filter(cyl == .cyl)
xsym <- rlang::ensym(.pred)
rlang::inject( lm(mpg ~ !!xsym, data = tmp) ) %>%
tidy() %>%
mutate(cylinders = .cyl)
}
最佳答案
替代方法,使用glue
库:
regr_func <- function(.cyl, .pred){
require(glue)
o <- 'mpg ~ {.pred}' %>% glue
lm(o, data = mtcars %>% subset(cyl == .cyl))
}
关于r - 将参数传递给使用 dplyr R 的函数内的回归模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69719609/