2
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

gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79
Oscar
  • 41
  • 1
  • 6
  • 1
    Would be easier to reshape the data to long format and use lmList from package nlme. – Roland Oct 09 '19 at 15:59
  • Take a look at `broom` package. These might be useful https://stackoverflow.com/a/55194281/786542 & https://stackoverflow.com/a/49484854/786542 & https://stackoverflow.com/a/54624775/786542 – Tung Oct 09 '19 at 16:38

1 Answers1

1

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
gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79