【问题标题】:regression output in dplyrdplyr 中的回归输出
【发布时间】:2016-02-28 19:13:49
【问题描述】:

我想定义与“扫帚”包中类似的功能

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()) 中的错误: “字符”类型的无效“环境”参数

【问题讨论】:

    标签: r regression dplyr


    【解决方案1】:

    glance 以这种方式工作是因为 broom 包为行数据帧 here 定义了一个方法。如果您愿意引入整个 .R 文件(以及来自 herecol_name 实用程序),您可以使用我的代码来做同样的事情:

    myglance_df <- wrap_rowwise_df(wrap_rowwise_df_(myglance))
    
    mtcars %>% 
      group_by(am) %>% 
      do(model = lm(mpg ~ wt, .)) %>% 
      myglance_df(model)
    

    还有一个不需要从扫帚添加太多代码的解决方法:更改每个模型的 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, .)))
    

    【讨论】:

    • 非常感谢您的包裹和您的详细回答!
    【解决方案2】:

    这是我对其工作方式的看法,基本上方法是:

    1. 从dataframe中提取相应的列(我的解决方案是基于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://stackoverflow.com/a/21629102/1992167
    
      # 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2021-05-25
      • 2017-01-25
      • 2019-05-26
      • 2018-08-29
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多