简体   繁体   English

用于提取值的 R 循环

[英]R Loop For Extracting Values

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]]

The code above generates a series of simple regression models for different independent variables.上面的代码为不同的自变量生成了一系列简单的回归模型。 My priority is to then extract the coefficient and standard error for each of the variables listed in varlist.我的首要任务是提取 varlist 中列出的每个变量的系数和标准误差。 My attempt shows below.我的尝试如下所示。

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

My hopeful output will show three columns--variable, coefficient, std.我充满希望的 output 将显示三列——变量、系数、标准。 error:错误:

在此处输入图像描述

How about:怎么样:

ATTEMPT2 = lapply(1:length(models), function(x) {
                    cf <- coef(summary(models[[x]]))
                    data.frame(Variable=rownames(cf)[2], 
                               Estimate=cf[2,1],
                               Std.Error=cf[2,2])})
(df2 <- do.call("rbind", ATTEMPT2))
#   Variable  Estimate  Std.Error
# 1    write 0.6455300 0.06168323
# 2     math 0.7248070 0.05827449
# 3  science 0.6525644 0.05714318
# 4    socst 0.5935322 0.05317162

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM