dplyr 中的回归输出

regression output in dplyr

我想定义与 'broom' 包中类似的功能

library(dplyr)
library(broom)

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

工作正常。但是我如何定义像

这样的自定义函数
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)

eval(substitute(expr), data, enclos = parent.frame()) 错误: 类型 'character'

的参数无效 'envir'

这是我对它的工作原理的看法,基本上方法是:

  1. 从数据框中提取适当的列(我的解决方案是基于this answer,那里一定是更好的方法,我希望有人会纠正我的!

  2. 运行 lapply 并在上面的 myglance 函数中构造您想要的变量。

  3. 运行 do.callrbind 至 return 一 data.frame.


myglance <- function(df, ...) {
  # step 1
  s <- collect(select(df, ...))[[1]] # based on this answer: 

  # 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

glance 以这种方式工作,因为 broom 包定义了一种用于行数据框的方法 here. If you were willing to bring in that whole .R file (along with the col_name utility from here),您可以使用我的代码来做同样的事情:

myglance_df <- wrap_rowwise_df(wrap_rowwise_df_(myglance))

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

还有一个解决方法不需要从 broom 添加那么多代码:更改每个模型的 class,然后定义 拥有 glance 功能 class.

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, .)))