的下面是与较小的数据和基R(不使用data.table
)的一个例子。
#DATA
set.seed(42)
dt <- data.table(group=rep(1:5, each = 20), value = rnorm(20 * 5))
这是通过首先获得独特的元素的列表group
,然后运行value
之间cor
对应于所有对独特group
。
groups = unique(dt$group)
sapply(1:length(groups), function(i)
sapply(1:length(groups), function(j)
cor(x = dt$value[dt$group == groups[i]], y = dt$value[dt$group == groups[j]])))
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1.00000000 0.436949356 0.04324370 -0.03960938 0.281518699
#[2,] 0.43694936 1.000000000 0.03976509 -0.06555478 0.005944951
#[3,] 0.04324370 0.039765093 1.00000000 0.33289052 0.211291403
#[4,] -0.03960938 -0.065554780 0.33289052 1.00000000 -0.183091610
#[5,] 0.28151870 0.005944951 0.21129140 -0.18309161 1.000000000
另一种办法也没有工作重铸但需要拆分成dt
基于group
列表。
temp = split(dt, dt$group)
sapply(1:length(temp), function(i)
sapply(1:length(temp), function(j)
cor(x = temp[[i]]$value, y = temp[[j]]$value)))
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1.00000000 0.436949356 0.04324370 -0.03960938 0.281518699
#[2,] 0.43694936 1.000000000 0.03976509 -0.06555478 0.005944951
#[3,] 0.04324370 0.039765093 1.00000000 0.33289052 0.211291403
#[4,] -0.03960938 -0.065554780 0.33289052 1.00000000 -0.183091610
#[5,] 0.28151870 0.005944951 0.21129140 -0.18309161 1.000000000
我刚刚在一个循环中做了这件事,看起来这不仅仅是为了做两个for循环而更容易阅读或理解。 –