簡體   English   中英

將參數傳遞給使用 dplyr R 的函數內的回歸模型

[英]Passing an argument to a regression model inside a function that uses dplyr R

我編寫了一個函數來對過濾后的數據集運行單變量回歸。 該函數將用於過濾的值和回歸模型的預測變量的名稱作為參數。 如您所見,我正在努力處理數據屏蔽和評估。 如何直接在回歸模型中使用 .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))
}

您可以使用as.formula即時創建公式或reformulate公式而不會破壞管道。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM