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
397 views
in Technique[技术] by (71.8m points)

r - Linear Regression loop for each independent variable individually against dependent

I want to figure out how to create a loop or using one of the apply functions to get individual 1:1 regression information for each variable in a dataset against the dependent variable.

Lets say I am using mtcars. How would I write in R code that takes each variable in the data frame and regresses it against MPG?

Even better would be getting a summary of each independent variable with and having some sort of name assignment such as x1=, x2=etc

summary(lm(mpg~eachvar,data=mtcars))
Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

This will do it for you.

lapply( mtcars[,-1], function(x) summary(lm(mtcars$mpg ~ x)) )

A data.frame object is a list with some other features so this will go through each column of mtcars excluding the first one and perform the regressions. If you save the resulting list in something like L then you can access each one easily by just using the same name or number as the column in the original data.frame. So L$cyl gives the regression summary for mpg on cyl.


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

...