数据表中的相关矩阵

use*_*689 5 r correlation data.table

如果我有以下数据表:

set.seed(1)
TDT <- data.table(Group = c(rep("A",40),rep("B",60)),
                      Id = c(rep(1,20),rep(2,20),rep(3,20),rep(4,20),rep(5,20)),
                      Time = rep(seq(as.Date("2010-01-03"), length=20, by="1 month") - 1,5),
                      norm = round(runif(100)/10,2),
                      x1 = sample(100,100),
                      x2 = round(rnorm(100,0.75,0.3),2),
                      x3 = round(rnorm(100,0.75,0.3),2),
                      x4 = round(rnorm(100,0.75,0.3),2),
                      x5 = round(rnorm(100,0.75,0.3),2))
Run Code Online (Sandbox Code Playgroud)

如何通过时间计算x1,x2,x3,x4和x5之间的相关性?

这个:

TDT[,x:= list(cor(TDT[,5:9])), by = Time]
Run Code Online (Sandbox Code Playgroud)

不起作用。

怎么做datatable呢?

Jea*_*lie 3

你的尝试是如此接近!你错过的只是一个额外的list()

这有效:

TDT[,x:= list(list(cor(TDT[,5:9]))), by = Time]
Run Code Online (Sandbox Code Playgroud)

TDT$x返回:

[[1]]
            x1          x2          x3         x4          x5
x1  1.00000000  0.72185099  0.07368766 -0.7031890 -0.36895449
x2  0.72185099  1.00000000  0.68058833 -0.7393130  0.05066973
x3  0.07368766  0.68058833  1.00000000 -0.5021462  0.10645894
x4 -0.70318896 -0.73931299 -0.50214616  1.0000000  0.11671020
x5 -0.36895449  0.05066973  0.10645894  0.1167102  1.00000000

[[2]]
           x1         x2          x3          x4         x5
x1  1.0000000 -0.1011948 -0.85191422 -0.15571603  0.4855237
x2 -0.1011948  1.0000000  0.56691559 -0.44002621 -0.6699172
x3 -0.8519142  0.5669156  1.00000000  0.02189754 -0.6168013
x4 -0.1557160 -0.4400262  0.02189754  1.00000000  0.2236542
x5  0.4855237 -0.6699172 -0.61680132  0.22365419  1.0000000

[...]
Run Code Online (Sandbox Code Playgroud)

list()由于如何data.table解析语法的第二个元素,因此需要额外的内容DT[1,2]。这已经在 stackoverflow 的其他地方进行了深入讨论,我邀请您阅读一个非常优秀的答案。

作为旁注,似乎最好将最外层的调用替换为list()with.()以澄清意图。我还喜欢明确指出引用.SD和 的列.SDcols。获得相同的结果,您可以将代码重写为:

TDT[, x := .(list(cor(.SD))), by = Time, .SDcols = 5:9]
Run Code Online (Sandbox Code Playgroud)