idpd15
idpd15

Reputation: 456

How to do linear regression with this particular data set?

I have a response variable y.
Also I have a list of 5 dependent variables

x <- list(x1, x2, x3, x4, x5)

Lastly I have a Logical Vector z of length 5. E.g.

z <- c(TRUE, TRUE, FALSE, FALSE, TRUE)  

Given this I want R to automatically do linear Regression

lm(y ~ x1 + x2 + x5)

Basically the TRUE/FALSE correspond to whether to include the dependent variable or not.
I am unable to do this.
I tried doing lm(y ~x[z]) but it does not work.

Upvotes: 1

Views: 223

Answers (2)

user10313669
user10313669

Reputation:

Try something like binding your y to a data.frame or matrix (cbind) before you do your linear regression. You can filter your dependent variables by doing something like this:

x <- list(x1 = 1:5, x2 = 1:5, x3 = 1:10, x4 = 1:5, x5 = 1:5)
z <- c(TRUE, TRUE, FALSE, FALSE, TRUE)
b <- data.frame(x[which(z == TRUE)])

Upvotes: 1

Julius Vainora
Julius Vainora

Reputation: 48241

You may do

lm(y ~ do.call(cbind, x[z]))

do.call(cbind, x[z]) will convert x[z] into a matrix, which is an acceptable input format for lm. One problem with this is that the names of the regressors (assuming that x is a named list) in the output are a little messy. So, instead you may do

lm(y ~ ., data = data.frame(y = y, do.call(cbind, x[z])))

that would give nice names in the output (again, assuming that x is a named list).

Upvotes: 1

Related Questions