Regress each column in a data frame on a vector in R

r, statistics

Solution

This will do what you want, assuming your data.frame is called 'd'

r2s <- apply(d, 2, function(x) summary(lm(x ~ HAPPY))$r.squared)
names(d)[which.max(r2s)]

You can find out how to extract components of the model, or in this case, a summary of the model, with the str() command. It will give you a read out that helps you access the components of any complex object.

Problem

I want to regress each column in a data set on a vector then return the column which has the highest R-squared value. e.g. I have a vector HAPPY <- (3,2,2,3,1,3,1,3) and I have a data set. ``` HEALTH CONINC MARITAL SATJOB1 MARITAL2 HAPPY 3 441 5 1 2 3 1 1764 5 1 2 2 2 3087 5 1 2 2 3 3087 5 1 2 3 1 3969 2 1 5 1 1 3969 5 1 2 3 2 4852 5 1 2 2 3 5734 3 1 3 3 ``` Regress "Happy" on each of the columns in the data set on the left, then return the column which has the highest R-squared. Example: lm(Health ~ Happy) if Health had the highest R-squared value, then return Health. I've tried apply, but can't seem to figure out how to return the regression with the highest R-squared. Any suggestions?

Original source