Regression output in dplyr

I would like to define similar features as in the broom package

library(dplyr)
library(broom)

mtcars %>% 
  group_by(am) %>% 
  do(model = lm(mpg ~ wt, .)) %>% 
  glance(model)

works great. But how do I cancel custom features like

myglance <- function(x, ...) {
  s <- summary(x)
  ret <- with(s, data.frame(r2=adj.r.squared, a=coefficients[1], b=coefficients[2]))
  ret
}


mtcars %>% 
  group_by(am) %>% 
  do(model = lm(mpg ~ wt, .)) %>% 
  myglance(model)

Error in eval (substitute (expr), data, enclos = parent.frame ()): invalid argument 'envir' of type 'character'

+4
source share
2 answers

glanceworks this way because a broom package defines a method for cropping data frames here . If you want to include this entire .R file (along with the utility col_namefrom here ), you can use my code to do the same:

myglance_df <- wrap_rowwise_df(wrap_rowwise_df_(myglance))

mtcars %>% 
  group_by(am) %>% 
  do(model = lm(mpg ~ wt, .)) %>% 
  myglance_df(model)

, : .

glance.mylm <- function(x, ...) {
  s <- summary(x)
  ret <- with(s, data.frame(r2=adj.r.squared, a=coefficients[1], b=coefficients[2]))
  ret
}

mtcars %>% 
  group_by(am) %>% 
  do(model = lm(mpg ~ wt, .)) %>% 
  mutate(model = list(structure(model, class = c("mylm", class(model))))) %>%
  glance(model)

, myglance .

mtcars %>% 
  group_by(am) %>% 
  do(myglance(lm(mpg ~ wt, .)))
+3

, , :

  • ( , , , - !

  • lapply , myglance, .

  • do.call rbind, data.frame.


myglance <- function(df, ...) {
  # step 1
  s <- collect(select(df, ...))[[1]] # based on this answer: /questions/67774/extract-a-dplyr-tbl-column-as-a-vector/461605#461605

  # step 2
  lapply(s, function(x) {
    data.frame(r2 = summary(x)$adj.r.squared,
               a = summary(x)$coefficients[1],
               b = summary(x)$coefficients[2])
  }) %>% do.call(rbind, .) # step 3
}

:

> mtcars %>% 
+   group_by(am) %>% 
+   do(model = lm(mpg ~ wt, .)) %>%
+   myglance(model)
         r2        a         b
1 0.5651357 31.41606 -3.785908
2 0.8103194 46.29448 -9.084268
+1

Source: https://habr.com/ru/post/1617512/


All Articles