如何使用lapply代替嵌套的for循环来获取两个数据帧之间的相关性?

问题描述 投票:0回答:1

我想通过将两个数据帧关联在一起来获得估计值、统计量和 p 值。我知道如何使用嵌套 for 循环或使用并行化的 foreach 来做到这一点。但是,我不知道如何使用 lappply 来做到这一点。

一个数据框有 10 行 15 列,另一个数据框有 10 行 20 列。

   df1 <- as.data.frame(matrix(runif(10*15, -1, 1), ncol=15))
   df2 <- as.data.frame(matrix(runif(10*20, -1, 1), ncol=20))

  colnames(df1) <- paste0("a", 1:ncol(df1))
  colnames(df2) <- paste0("b", 1:ncol(df2))

  combo <- expand.grid(colnames(df1), colnames(df2)) ##300 combinations

理想情况下,行名称将显示两个数据框之间的组合(组合),然后有一列用于估计、统计和 p 值,例如

   x <- list(df1,df2)

   res1 <- lapply(x, function(x) cor.test(x[, 1], x[, 2], method="spearman"))
   res2 <- lapply(res1, "[", c("estimate", "statistic", "p.value"))
   stats <- do.call(rbind, lapply(res2, unlist))

   stts <- c('estimate', 'statistic', 'p.value')
   out <- lapply(x, function(x) cor.test(x[,2], x[,3], method="spearman" [stts])) %>% do.call(what=rbind)


            estimate    statistic    p.value   
   
   a1:b1
   a1:b2
   a1:b3
   a1:b4
r nested-loops lapply correlation
1个回答
0
投票

试试这个:

library(tidyverse)

stts <- c('estimate', 'statistic', 'p.value')

res <- map(df1, function(l1) {
        map(df2,
            function(l2) {
                    cor.test(l1 , l2, method = "spearman")[stts] |> bind_rows()
            })
})

res <- bind_rows(lapply(res, function(l1) {
        bind_rows(l1, .id = "b")
}), .id = "a")

res <- res |> unite(rn, c(a,b), sep = ":") |> column_to_rownames("rn")

输出

            estimate statistic     p.value
a1:b1   -0.078787879       178 0.838004095
a1:b2   -0.127272727       186 0.732886836
a1:b3   -0.406060606       232 0.247370788
a1:b4   -0.733333333       286 0.021166481
a1:b5   -0.539393939       254 0.113298067
.
.
.
© www.soinside.com 2019 - 2024. All rights reserved.