dplyr中的回归输出

4

我想定义与“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函数执行时出错,错误信息为“在eval(substitute(expr), data, enclos = parent.frame())中,无效的'envir'参数类型为'character'”

2个回答

3

glance的工作方式是这样的,因为broom包在这里定义了一种适用于按行数据框的方法。如果您愿意将整个.R文件(以及这里的col_name实用程序)引入,您可以使用我的代码来完成同样的事情:

myglance_df <- wrap_rowwise_df(wrap_rowwise_df_(myglance))

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

还有一种方法可以绕过使用broom添加大量代码的问题:更改每个模型的class,并在该类上定义您自己的glance函数。

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

非常感谢您提供的程序包和详尽的解答! - ckluss

1
这是我对它的理解,基本上的方法如下:
  1. 从数据框中提取适当的列(我的解决方案基于this answer,肯定有更好的方法,我希望有人能纠正我!)

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

  3. 使用do.callrbind运行,返回一个data.frame


myglance <- function(df, ...) {
  # step 1
  s <- collect(select(df, ...))[[1]] # based on this answer: https://dev59.com/_2Ei5IYBdhLWcg3wIJFH#21629102

  # 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接