遍历列表中的两个变量

时间:2019-10-24 15:34:45

标签: r loops

我有一个带有距离矩阵的列表:

obs <- list(AA=list(A=dist(runif(100)),
                 B=dist(runif(100)),
                 C=dist(runif(100))),
            BB=list(A=dist(runif(100)),
                    B=dist(runif(100)),
                    C=dist(runif(100))))

obs <- lapply(obs, function(x)
  lapply(x, function(x) as.data.frame(as.matrix(x))))

还有一个只有一个等级的人:

distances <- lapply(list(A=rnorm(100),B=rnorm(100),C=rnorm(100)), function(x)
  as.data.frame(as.matrix(dist(x, "euclidean"))))

我想比较obs第二级和distances第一级中的所有矩阵,如果它们的名称匹配(obs[i]$Adistances$A, B与B,C与C;永远不会所有组合!)。尝试在lapply中运行sapply失败后,我进入了for循环,在此期间我存储结果并从中提取一些值:

coef <- pvals <- res <- vector("list", length(names(obs)))
library(vegan)
for(i in (names(obs)){ 
  res[[i]]$A  <- mantel(obs[[i]]$A, distances$A, "spearman", perm=999)
  #tmp <-  res[[i]]$A
  #coef[i]$A <- tmp[i]$statistic
  #pvals[i]$A <- tmp[i]$signic
}

我遍历第一级obs并修复第二级,然后针对obs[[i]]$AB进行此操作(不要从上方再次粘贴#行以节省空间):

    for(i in (names(obs)){ 
      res[[i]]$B  <- mantel(obs[[i]]$B, distances$B, "spearman", perm=999)
      ...
    }
    for(i in (names(obs)){ 
      res[[i]]$C  <- mantel(obs[[i]]$C, distances$C, "spearman", perm=999)
      ...
    }

现在的问题是也要遍历第二级(obs[i]$A,B,C),同时还要指向distances中的正确矩阵。将上面的三个循环放到一个家长循环中(通过obs [i] [j])会更好还是有办法使用lapply?谢谢!

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,我会做这样的事情:

[Violation] 'setTimeout' handler took 109ms
[Violation] 'click' handler took 206ms
[Violation] Forced reflow while executing JavaScript took 72ms
[Violation] 'click' handler took 204ms
[Violation] 'click' handler took 390ms
[Violation] Forced reflow while executing JavaScript took 180ms
[Violation] 'animationend' handler took 13282ms
[Violation] 'animationend' handler took 13341ms
[Violation] Forced reflow while executing JavaScript took 12864ms
[Violation] 'click' handler took 171ms