简体   繁体   中英

Using nested lapply with linear regression (R)

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.

I have worked this out now by reworking the various lapply(s). The below does what I needed, in case it helps anyone else.

result = lapply(predictor_variable, function(x) (data.frame(lapply(lapply(lapply(target_variable, function(y) lm(x ~ y + covariate1 + covariate2, data = Data)), summary), function(x) x$coefficients[2, c(1:4)]))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM