FreshF
FreshF

Reputation: 381

Using apply to loop over different datasets in a regression

I found this way of looping over variables in an lm() when the variable names are stored as characters (http://www.ats.ucla.edu/stat/r/pages/looping_strings.htm):

models <- lapply(varlist, function(x) {
    lm(substitute(read ~ i, list(i = as.name(x))), data = hsb2)
})

My first question is: Is there a more efficient/faster way?

What if I want to loop over different data instead of looping over variables?

Example:

reg1 <- lm(a~b, data=dataset1)
reg2 <- lm(a~b, data=dataset2)

Can I apply something similar to the code shown above? Using the substitute function for the data did not work.

Thank You!

Upvotes: 0

Views: 2512

Answers (1)

Sebastian
Sebastian

Reputation: 850

The substitute in your example is used to construct the formula. If you want to to apply lm to a number of data.frames use:

lapply(list(dataset1, dataset2), lm, formula = a ~ b)

Upvotes: 2

Related Questions