R提取值的循环

问题描述 投票:0回答:1
hsb2 <- read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv")
names(hsb2)
varlist <- names(hsb2)[8:11]

models <- lapply(varlist, function(x) {
  lm(substitute(read ~ i, list(i = as.name(x))), data = hsb2)
})

## look at the first element of the list, model 1
models[[1]]

上面的代码为不同的自变量生成了一系列简单的回归模型。我的首要任务是为varlist中列出的每个变量提取系数和标准误差。我的尝试如下所示。

ATTEMPT = lapply(1:length(models), function(x) {
                   cbind(cov, coef(summary(models[[x]]))[2,1:2])})

我希望的输出将显示三列-变量,系数,标准。错误:

enter image description here

r dplyr data.table lapply mapply
1个回答
0
投票

怎么样:

ATTEMPT2 = lapply(1:length(models), function(x) {
                    cf <- coef(summary(models[[x]]))
                    data.frame(variable=rownames(cf)[2], 
                               estimate=cf[2,1],
                               std.err=cf[2,2])})
(df2 <- do.call("rbind", ATTEMPT2))
#   variable  estimate    std.err
# 1    write 0.6455300 0.06168323
# 2     math 0.7248070 0.05827449
# 3  science 0.6525644 0.05714318
# 4    socst 0.5935322 0.05317162
© www.soinside.com 2019 - 2024. All rights reserved.