简体   繁体   English

将嵌套 lapply 与线性回归 (R) 结合使用

[英]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.我对 R 很陌生,正在使用 lapply 运行多元线性回归分析,并将关键统计数据 output 放入表格中。

it works well initially, but I cannot get it to work when I nest one lapply within another...它最初运行良好,但是当我将一个 lapply 嵌套在另一个 lapply 中时,我无法让它工作......

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.但是,我想将其嵌套在进一步的 lapply 中,以改变 predictor_variable 。

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.同样,这最初有效,但我正在努力提取摘要(使用:lapply(结果,摘要)),如第一个示例所示。 I am guessing this is easy to do, and have tried using for loops, but the output doesn't work as intended.我猜这很容易做到,并尝试使用 for 循环,但 output 没有按预期工作。 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).我现在通过修改各种 lapply 来解决这个问题。 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)]))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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