dplyr,do(),从模型中提取参数而不会丢失分组变量

dan*_*res 7 r dplyr

来自R帮助do()的稍微改变的例子:

by_cyl <- group_by(mtcars, cyl)
models <- by_cyl %>% do(mod = lm(mpg ~ disp, data = .))
coefficients<-models %>% do(data.frame(coef = coef(.$mod)[[1]]))
Run Code Online (Sandbox Code Playgroud)

在数据帧系数中,每个cyl组都有第一个线性模型系数.我的问题是如何生成一个数据框,其中不仅包含具有系数的列,还包含具有分组变量的列.

=====编辑:我扩展示例以尝试更清楚我的问题

让我们假设我想提取模型的系数和一些预测.我可以做这个:

by_cyl <- group_by(mtcars, cyl)
getpars <- function(df){
  fit <- lm(mpg ~ disp, data = df)
  data.frame(intercept=coef(fit)[1],slope=coef(fit)[2])
}
getprediction <- function(df){
  fit <- lm(mpg ~ disp, data = df)
  x <- df$disp
  y <- predict(fit, data.frame(disp= x), type = "response")
  data.frame(x,y)
}
pars <- by_cyl %>% do(getpars(.))
prediction <- by_cyl %>% do(getprediction(.))
Run Code Online (Sandbox Code Playgroud)

问题是代码是多余的,因为我适合模型两次.我的想法是构建一个返回包含所有信息的列表的函数:

getAll <- function(df){
  results<-list()
  fit <- lm(mpg ~ disp, data = df)
  x <- df$disp
  y <- predict(fit, data.frame(disp= x), type = "response")

  results$pars <- data.frame(intercept=coef(fit)[1],slope=coef(fit)[2])
  results$prediction <- data.frame(x,y)

  results
 }
Run Code Online (Sandbox Code Playgroud)

问题是我不知道如何使用函数getAll来使用do()来获取例如带有参数的数据帧(如数据帧文件).

Rob*_*ski 7

像这样?

coefficients <-models %>% do(data.frame(coef = coef(.$mod)[[1]], group = .[[1]]))
Run Code Online (Sandbox Code Playgroud)

生产

        coef group
  1 40.87196     4
  2 19.08199     6
  3 22.03280     8
Run Code Online (Sandbox Code Playgroud)