Reputation: 33
I've created code to run the lm command multiple times with different variables:
DVs <- c('mpg', 'wt')
lapply(DVs, function(x)
lm(substitute(scale(DV) ~ scale(disp)+scale(qsec), list(DV = as.name(x))), data=mtcars))
However, I would like to be able to create a nested loop, to iterate through another variable as well. The code I have used to attempt that is:
DVs <- c('mpg', 'wt')
IVs <- c('disp', 'hp')
lapply(DVs, function(x) lapply(IVs, function(y)
lm(substitute(substitute(scale(DV) ~ scale(IV)+scale(qsec), list(DV = as.name(x)), list(IV = as.name(y)), data=mtcars)))))
However this leads to an error:
Error in substitute(scale(DV) ~ scale(IV) + scale(qsec), list(DV = as.name(x)), : unused arguments (list(IV = as.name(X[[i]])), data = mtcars)
How can I make this nested loop work?
Upvotes: 2
Views: 559
Reputation: 33
Thanks for the suggestion Josh O'Brien! This worked:
DVs <- c('mpg', 'wt')
IVs <- c('disp', 'hp')
lapply(DVs, function(x) lapply(IVs, function(y) {lm(reformulate(response=x, termlabels=y), data=mtcars)}))
I couldn't figure out how to scale my data within the call, but I can just scale my whole dataframe:
mtcarsSC <- as.data.frame(scale(mtcars))
DVs <- c('mpg', 'wt')
IVs <- c('disp', 'hp')
lapply(DVs, function(x) lapply(IVs, function(y) {lm(reformulate(response=x, termlabels=y), data=mtcarsSC)}))
Upvotes: 1