I am quite new to R and am using lapply to run multiple linear regression analyses, and output the key statistics into a table.
it works well initially, but I cannot get it to work when I nest one lapply within another...
When I use the below, it works well, and outputs the various coefficients conveniently in a table.
var1 = target_variables #(multiple columns)
results <-lapply(var1, function(x) lm(x ~ predictor_variable + covariate1 + covariate2, data = Data))
summaries <- lapply(results, summary)
sapply(summaries, function(x) x$coefficients[2, c(1:4)])
However, I would like to nest this within a further lapply, to vary the predictor_variable too.
var1 = target_variables #(multiple columns)
var2 = predictor_variables # (multiple columns)
results <-lapply(var2, function(y) lapply(var1, function(x) (lm(x ~ y + covariate1 + covariate2))))
Again, this works, initially, but I am struggling with extracting the summaries (using: lapply(results, summary)), as in the first example. I am guessing this is easy to do, and have tried using for loops, but the output doesn't work as intended. I think I just need an easy way to access all of the '2nd layer' in the nested list.
Example initial loop below if of interest, but I am sure there must be an easier way (that works!). I know I would need to have a second loop, but just testing the concept.
results <- c()
for (x in 1:length(var2)) {
result <- summary(results[[x]][[1]])
results <- append(results, result)
}
Any help would be much appreciated.