【问题标题】:Passing an argument to a regression model inside a function that uses dplyr R将参数传递给使用 dplyr R 的函数内的回归模型
【发布时间】:2021-10-26 08:10:52
【问题描述】:

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

【问题讨论】:

  • 直接进入回归模型是什么意思?要删除这部分吗?:mutate(x = .data[[.pred]])
  • 我认为这个相关的答案提供了一些适用的方法:stackoverflow.com/q/65527715/6851825
  • @Shibaprasadb 是的,没错。
  • 谢谢@JonSpring,它解决了传递参数的问题,但代价是能够将数据通过管道传输到 lm() 函数中。

标签: r dplyr evaluation


【解决方案1】:

替代方法,使用glue 库:

regr_func <- function(.cyl, .pred){
  require(glue)
  o <- 'mpg ~ {.pred}' %>% glue
  lm(o, data = mtcars %>% subset(cyl == .cyl))
}

【讨论】:

    【解决方案2】:

    您可以使用as.formulareformulate 即时创建公式,而不会破坏管道。

    library(dplyr)
    library(broom)
    
    regr_func <- function(.cyl, .pred){
      
      mtcars %>% 
        filter(cyl == .cyl) %>%  
        lm(reformulate(.pred, 'mpg'), data = .) %>% 
        tidy() %>% 
        mutate(predictor = .pred,
               cylinders = .cyl)
    }
    regr_func(4, "hp")
    
    #  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 hp            -0.113    0.0612     -1.84 0.0984    hp                4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      相关资源
      最近更新 更多