0

I want to estimate the following regression models:

y <- rnorm(1:100)
x1 <- 1:100
x2 <- 1:100
x3 <- 1:100

my_data <- data.frame(cbind(y, x1, x2, x3))

m1 <- lm(y ~ x1, data = my_data)
m2 <- lm(y ~ x2, data = my_data)
m3 <- lm(y ~ x3, data = my_data)

I want to run several models like this, using the same dataset and a different independent variable in each model. How can I use a loop to run each model?

1 Answer 1

1

This can be easily accomplished using the apply() function:

data_to_analyse <- my_data[, -1] # leave out the y column for this analysis

out <- apply(data_to_analyse, 2, function(current_col){

lm.out <- lm(my_data$y ~ current_col)

})

This takes each column of the data.frame ("current_col") and then performs linear regression. The output of the function is a list containing the results of each regression, each entry named by the variable name.

Sign up to request clarification or add additional context in comments.

1 Comment

For easier comparison, you could broom::tidy the output before placing it in a list, and then dplyr::bind_rows to get one dataframe with all your results. Be sure to include .id = "name" in your bind_rows to be able to separate which output comes from which column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.