r - 将参数传递给使用 dplyr R 的函数内的回归模型

标签 r dplyr evaluation

我编写了一个函数来对过滤后的数据集运行单变量回归。该函数将用于过滤的值和回归模型的预测变量名称作为参数。如您所见,我正在努力处理数据屏蔽和评估。如何在回归模型中直接使用 .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/

相关文章:

javascript - ' ' 和 ""以及没有引号在 Javascript 中是什么意思?

language-agnostic - 如何评估文本摘要工具?

c++ - 在使用 C++ 中的堆栈评估后缀时处理十进制值

python - 从 Gmail 下载子文件夹

regex - 具有前瞻性的 R 正则表达式中的贪婪

r - 如何应用 `mutate_at` 内的函数,该函数按行条件影响其他列中的值?

r - 为什么 dplyr 的 top_n() 不起作用?

r - 如何移动嵌套 tibbles 中的 tibbles 列?

r - 如何快速执行类似乘法的矩阵运算?

r - 识别时间序列中重复的数字序列