gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:32:23 25 4
gpt4 key购买 nike

来自 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]]))

在数据帧系数中,每个 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(.))

问题是代码是多余的,因为我对模型进行了两次拟合。我的想法是构建一个返回包含所有信息的列表的函数:
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
}

问题是我不知道如何将 do() 与函数 getAll 一起使用来获取例如带有参数的数据帧(如数据帧解析)。

最佳答案

像这样?

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

关于r - dplyr, do(), 在不丢失分组变量的情况下从模型中提取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24587803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com