R Loop For Extracting Values

Viewed 99
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. 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. error:

enter image description here

1 Answers

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
Related