How do I perform stepwise regression analyses with dplyr pipes?

Viewed 134

In order to increase readability, I want to filter my data frame before I pipe it into a regression model. For some reason - however - this does not seem to be possible.

I can write something like:

model<-lm(mpg~.,data=mtcars)%>%¨
stepAIC(trace = FALSE)

....And that works perfectly, even with the pipe at the end. But then I try to replace the data argument with a placeholder:

model<-df%>%lm(mpg~.,data=.)%>%
stepAIC(trace = FALSE)

....And I get an error claiming that:

Error in as.data.frame.default(data) : 
cannot coerce class ‘"lm"’ to a data.frame

This issue only seems to occur when I'm using the stepAIC-function. Unfortunatly that's a requirement for my current project.

Can I make this work and in that case how?

1 Answers

the stepAIC part needs to see the dataframe from the environment, I tried passing it in many ways but it's problematic. One option is that you can try and still get the results is:

library(purrr)
library(dplyr)
library(MASS)

list(mtcars) %>% map(~stepAIC(lm(mpg~.,data=.),trace=FALSE))
[[1]]

Call:
lm(formula = mpg ~ wt + qsec + am, data = .)

Coefficients:
(Intercept)           wt         qsec           am  
      9.618       -3.917        1.226        2.936  

Another way is, if you want to run the same fit over multiple datasets is to do:

# example dataset with bootstraps
sampledata = lapply(1:3,function(i){
mtcars[sample(nrow(mtcars),replace=TRUE),]
})

# nest it in a tibble
tibble(names=paste0("data",1:3),data=sampledata)
# A tibble: 3 x 2
  names data               
  <chr> <list>             
1 data1 <df[,11] [32 × 11]>
2 data2 <df[,11] [32 × 11]>
3 data3 <df[,11] [32 × 11]>

res = tibble(names=paste0("data",1:3),data=sampledata) %>% 
mutate(mdl=map(data,~stepAIC(lm(mpg~.,data=.x),trace=FALSE)))

res$mdl
[[1]]

Call:
lm(formula = mpg ~ disp + hp + drat + wt + qsec + am + gear, 
    data = .x)

Coefficients:
(Intercept)         disp           hp         drat           wt         qsec  
  -73.20988     -0.01714      0.03991      3.12230     -3.80928      4.08125  
         am         gear  
  -11.24742      7.17872  


[[2]]

Call:
lm(formula = mpg ~ disp + vs + am + carb, data = .x)

Coefficients:
(Intercept)         disp           vs           am         carb  
   26.14918     -0.02344      2.11914      5.17128     -1.25915  


[[3]]

Call:
lm(formula = mpg ~ wt + qsec + am + gear + carb, data = .x)

Coefficients:
(Intercept)           wt         qsec           am         gear         carb  
    -2.7017      -2.5837       1.4633       2.8117       1.8643      -0.8727  
Related