将回归结果输出到R中的数据帧中 [英] Outputting Regression results into a data frame in R
问题描述
我想知道是否有任何命令可以像在SAS中一样将lm模型的结果输出到R中的数据帧中. 有任何想法吗?我正在运行多个模型,并且我希望结果看起来像下面-
I was wondering if there is any command that can output the results of a lm model into a data frame in R like outest in SAS. Any ideas? I am running multiple models and I want the result to look like below -
Model | alpha | Beta | Rsquared | F | df |
model0 | 8.4 | ... | .... | ..| .. |
model1 | ... | ... | .... | ..| .. |
model2 | ... | ... | .... | ..| .. |
我拥有的数据是"ds",即-
The data i have is 'ds' which is -
X1 | X2 | Y1 |
.. | .. | .. |
.. | .. | .. |
.. | .. | .. |
.. | .. | .. |
我的代码是一个简单的lm代码-
And my code is a simple lm code -
model0 <- lm(Y1 ~ X1, ds)
model1 <- lm(Y1 ~ 1, ds)
model2 <- lm(Y1 ~ X1 + X2, ds)
推荐答案
我做的完全一样.当然,这里的困难是如果模型具有不同数量的系数-那么您将具有不同数量的列,这在data.frame中是不可能的.每个模型的列数必须相同.
I do exactly the same thing. The difficulty here is of course if the models have different number of coefficients - then you would have different number of columns, which is impossible in data.frame. You need to have the same number of columns for each model.
我通常将其用于glm
(这些代码段已被注释掉),但我已为您为lm
对其进行了修改:
I normally use it for glm
(these code snippets are commented out) but I modified it for lm
for you:
models <- c()
for (i in 1:10) {
y <- rnorm(100) # generate some example data for lm
x <- rnorm(100)
m <- lm(y ~ x)
# in case of glm:
#m <- glm(y ~ x, data = data, family = "quasipoisson")
#overdispersion <- 1/m$df.residual*sum((data$count-fitted(m))^2/fitted(m))
coef <- summary(m)$coef
v.coef <- c(t(coef))
names(v.coef) <- paste(rep(rownames(coef), each = 4), c("coef", "stderr", "t", "p-value"))
v.model_info <- c(r.squared = summary(m)$r.squared, F = summary(m)$fstatistic[1], df.res = summary(m)$df[2])
# in case of glm:
#v.model_info <- c(overdisp = summary(m)$dispersion, res.deviance = m$deviance, df.res = m$df.residual, null.deviance = m$null.deviance, df.null = m$df.null)
v.all <- c(v.coef, v.model_info)
models <- rbind(models, cbind(data.frame(model = paste("model", i, sep = "")), t(v.all)))
}
我更喜欢从summary(m)
获取数据.要将数据捆绑到data.frame
中,请使用cbind
(列绑定)和rbind
(行绑定)功能.
I prefer to take data from summary(m)
. To bundle the data into data.frame
, you use the cbind
(column bind) and rbind
(row bind) functions.
这篇关于将回归结果输出到R中的数据帧中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!