Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

r - How do you extract the coefficient and standard error from the lm() loop?

I was looking at this post on extracting coefficients from a regression loop. I was wondering how I would extract the coefficient and standard error? I thought it would be something like the following, but that appears to not be it:

data <- mtcars[, c("mpg", "cyl", "disp", "hp", "drat", "wt")]
col10 <- names(data)[-1]

lm.test <- vector("list", length(col10))

for(i in seq_along(col10)){
  lm.test[[i]] <- lm(reformulate(col10[i], "mpg"), data = data)
}

lm.test

cfs <- lapply(lm.test, coef[1:2])
question from:https://stackoverflow.com/questions/65909852/how-do-you-extract-the-coefficient-and-standard-error-from-the-lm-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ah, you got the famous "object of type closure is not subsettable" error.

We can use some [[ magic to help us here:

cfs <- lapply(lm.test, `[[`, "coefficients")

The double bracket is a function that extracts a variable name - this effectively loops over the following code:

cf_i <- lm.test[[i]][["coefficients"]]

where i is the number of models in lm.test

EDIT:

More simply,

cfs <- lapply(lm.test, coef)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...