假设我在R:中有一个这样的列表
> L
[[1]]
[1] 0.6876619 0.7847888 0.6377801 0.2078056 0.8981001
[[2]]
[1] 0.9358160 0.8905056 0.7715877 0.8648426 0.4915060
[[3]]
[1] 0.88095630 0.08010288 0.15140700 0.35400865 0.60317717
[[4]]
[1] 0.07436267 0.85873209 0.49881141 0.92363954 0.87208334
我想找到每对向量之间的相关系数,例如cor(L[[i]],L[[j]])
。有什么解决方案可以用apply
家族函数来执行它吗?请将其视为一个一般问题的具体情况:如果我们需要在R中的List((上进行三重嵌套循环怎么办
您可以嵌套lapply
调用:
lapply(L, function(x) lapply(L, function(y) cor(x,y))))
如果你想把结果呈现得更漂亮,可以把它们放在一个矩阵中:
L <- list(rnorm(10), rnorm(10), rnorm(10))
matrix(unlist(lapply(L,
function(x) lapply(L,
function(y) cor(x,y)))),
length(L))
#> [,1] [,2] [,3]
#> [1,] 1.0000000 -0.3880931 -0.4164212
#> [2,] -0.3880931 1.0000000 0.4158335
#> [3,] -0.4164212 0.4158335 1.0000000
创建于2021-05-31由reprex包(v2.0.0(
您可以使用mapply。生成所有感兴趣的组合(对、三元组…(,然后应用
L=replicate(5,rnorm(5),simplify=F)
tmp=expand.grid(1:length(L),1:length(L))
tmp$cor=mapply(
function(y,x){cor(L[[y]],L[[x]])},
tmp$Var1,
tmp$Var2
)
Var1 Var2 cor
1 1 1 1.0000000
2 2 1 0.1226881
3 3 1 -0.2871613
4 4 1 0.4746545
5 5 1 0.9779644
6 1 2 0.1226881
7 2 2 1.0000000
...
您可以cbind
列表并使用生成的matirx
调用cor
。
cor(do.call(cbind, L))
# [,1] [,2] [,3] [,4]
#[1,] 1.0000000 -0.46988357 0.14151672 0.14151672
#[2,] -0.4698836 1.00000000 -0.09177819 -0.09177819
#[3,] 0.1415167 -0.09177819 1.00000000 1.00000000
#[4,] 0.1415167 -0.09177819 1.00000000 1.00000000
如果列表中还有一个级别,请使用unlist
。
L2 <- lapply(L, list) #Create list with one more level.
cor(do.call(cbind, unlist(L2, FALSE)))
如果它是未知的或混合的,可以使用函数的递归调用:
L3 <- list(L[[1]], L[[2]], L2[[3]], L2[[4]])
f <- function(x) {
if(is.list(x)) sapply(x, f)
else x
}
cor(f(L3))
数据:
L <- list(c(0.6876619,0.7847888,0.6377801,0.2078056,0.8981001)
, c(0.9358160,0.8905056,0.7715877,0.8648426,0.4915060)
, c(0.88095630,0.08010288,0.15140700,0.35400865,0.60317717)
, c(0.88095630,0.08010288,0.15140700,0.35400865,0.60317717))