关联 r 中时间序列中的所有值对

Correlate all pairs of values in a time series in r

我正在尝试关联站点对中的时间序列数据。我正在处理如下所示的数据集:

A= 地点,B= 年份,C= 丰度:

         A    B    C
 [1,]    1 2002   21
 [2,]    1 2004   25
 [3,]    1 2005   26
 [4,]    2 3003   24
 [5,]    2 2004   20
 [6,]    2 2005   20
 [7,]    3 2002   21
 [8,]    3 2003   22
 [9,]    3 2004   23
[10,]    3 2005   25
 

我想按 A 列拆分数据以测试每个站点对之间的相关性(站点 1 与 2 和 3,站点 2 与 1 和 3 等)

我试过: mydata.cor = cor(dat, method = c("spearman"))

但这只是关联了列:

           A          B          C
A  1.0000000 -0.1287697 -0.1684834
B -0.1287697  1.0000000  0.4151682
C -0.1684834  0.4151682  1.0000000

有没有办法指定分组值,在本例中为网站类别?

一种方法是将数据转换为宽格式 然后按预期使用 cor()(在相关列上)。

这是我的可重现代码,我假设第 4 行中的 3003 是错字...

library(data.table)

mat <- matrix(c(
    1, 2002,   21,
    1, 2004,   25,
    1, 2005,   26,
    2, 2003,   24,
    2, 2004,   20,
    2, 2005,   20,
    3, 2002,   21,
    3, 2003,   22,
    3, 2004,   23,
    3, 2005,   25),10,3,byrow = TRUE)

DT <- data.table(mat)
names(DT) <- c("A","B","C")

DT_wide <- dcast(DT, B~A)
cor(DT_wide[,-1], method="spearman", use="pairwise.complete.obs")