Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
dplyr,do(),在不丢失分组变量的情况下从模型中提取参数_R_Dplyr - Fatal编程技术网

dplyr,do(),在不丢失分组变量的情况下从模型中提取参数

dplyr,do(),在不丢失分组变量的情况下从模型中提取参数,r,dplyr,R,Dplyr,do()的R帮助中有一个稍有改动的示例: 像这样 coefficients <-models %>% do(data.frame(coef = coef(.$mod)[[1]], group = .[[1]])) 使用哈德利·威克姆的方法: 库(dplyr) 图书馆(purrr) 图书馆(扫帚) fitmodel% 嵌套()%>% 变异(mod=map(数据,模型), pars=地图(mod,tidy), pred=映射(mod,augment)) PAR%unnest(PAR)

do()的R帮助中有一个稍有改动的示例:

像这样

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

使用哈德利·威克姆的方法:

库(dplyr)
图书馆(purrr)
图书馆(扫帚)
fitmodel%
嵌套()%>%
变异(mod=map(数据,模型),
pars=地图(mod,tidy),
pred=映射(mod,augment))
PAR%unnest(PAR)
预测%unnest(预测值)

谢谢,诸如此类。我想知道是否有可能自动使用group_by中的分组。因此,例如,如果group_by更改为group_by(mtcar,cyl,am),则不必在do()中使用group=.[1]]和group2=.[2]];试试
系数%do(data.frame(coef=coef(.$mod),group=.[1]],var=names(coef(.$mod))
我知道这一点很旧,但这确实帮助了我
do(data.frame(group=.[1]],a=coef(.$mod)[1],b=coef(.$mod)[2],r2=summary(.$mod)$r.squared))
这将获得整个方程,用于按变量绘制组。不确定这是否有帮助。您可以使用
summary
而不是第二个
do
。summary(models,coef=coef(summary(mod))[[1]],group=cyl)这是一个bug,我一弄清楚怎么解决它,就会马上修复它。@hadley这个问题解决了吗?你能指出github的问题吗?@RosenMatev你找到关于这个问题的任何东西了吗?根据Hadley的说法,它可能在dplyr 0.4中得到解决
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(.))
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
 }
coefficients <-models %>% do(data.frame(coef = coef(.$mod)[[1]], group = .[[1]]))
        coef group
  1 40.87196     4
  2 19.08199     6
  3 22.03280     8
library(dplyr)
library(purrr)
library(broom)

fitmodel <- function(d) lm(mpg ~ disp, data = d)
by_cyl <- mtcars %>% 
  group_by(cyl) %>% 
  nest() %>%
  mutate(mod = map(data, fitmodel), 
         pars = map(mod, tidy), 
         pred = map(mod, augment))

pars <- by_cyl %>% unnest(pars)
prediction <- by_cyl %>% unnest(pred)