Running several regressions with changing outcome variable in R

by melbez   Last Updated October 09, 2019 21:26 PM

I have a dataframe (df) that looks like the following:

condition  dv1  dv2  dv3
1          2    4    3
2          5    7    4
3          7    1    2

In order to run several regressions simultaneously, I have used code like this:

dfdv <- df[,2:4]  
output <- lm(as.matrix(dfdv) ~ condition, data = df)
summary(output)

This gives me all the dv ~ condition regressions for dv1, dv2, and dv3. These are the regressions that are given in the output:

dv1 ~ condition
dv2 ~ condition
dv3 ~ condition

However, I would now like to control for different conditions in the regression. Specifically, I would like to figure out a way to run the following regressions efficiently.

dv1 ~ condition + dv1
dv1 ~ condition + dv2
dv1 ~ condition + dv3

I tried the following using a similar principle to what worked above, and it didn't work:

dfdv <- df[,2:4]  
output2 <- lm(dv1 ~ condition + as.matrix(dfdv), data = df)
summary(output2)

Does anyone know how I can perform these regression analyses using simple code? I have several more in my actual dataset than I am including in this example.



Answers 1


We can use lapply for that

lapply(paste0("dv", 1:3), function(dv) lm(reformulate("condition", dv), data = df))
akrun
akrun
October 09, 2019 21:25 PM

Related Questions






R - regression and dummy seasonal variables

Updated February 19, 2017 20:26 PM