I am aware of several posts on this topic, see here Print and export loop from simple linear regression and here How to Loop/Repeat a Linear Regression in R.
However, I am interested in looping through not only a set of predictors but also a set of outcomes. Please see my code attempt below.
set.seed(42)
n <- 100
age <- runif(n, min=45, max=85)
sex <- factor(sample(c('Male','Female'), n, rep=TRUE, prob=c(.6, .4)))
smoke <- factor(sample(c("Never", 'Former', 'Current'), n, rep=TRUE, prob=c(.25, .6, .15)))
bmi <- runif(n, min=16, max=45)
outcome1 <- rbinom(n = 100, size = 1, prob = 0.3)
outcome2 <- rbinom(n = 100, size = 1, prob = 0.13)
predictorlist<- list("age","sex", "bmi", "smoke")
outcomelist <- list("outcome1","outcome2")
for (i in predictorlist){
for (j in outcomelist){
model <- lm(paste("j ~", i[[1]]))
print(summary(model))
}
}
In doing so I receive the following error message:
Error in model.frame.default(formula = paste("j ~", i[[1]]), drop.unused.levels = TRUE) :
variable lengths differ (found for 'age')
A quick check of their lengths reveals everything to be in order
> length(age)
[1] 100
> length(sex)
[1] 100
> length(bmi)
[1] 100
> length(smoke)
[1] 100
> length(outcome1)
[1] 100
> length(outcome2)
[1] 100
Any assistance is, naturally, tremendously appreciated.