0

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!

1
  • Do you need to change the formula in the lm Call output? Commented Sep 25, 2014 at 12:11

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

That is exactly what i needed! Do you also know how I can replace the data used in a for-loop?
Can you give a example?

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.