将 table 转换为相关类型矩阵

Converting a table to a correlation type matrix

我有 post-hoc 分析的结果。我想将其转换为相关类型矩阵

group1 <- c("1", "1", "2")
group2 <- c("2", "3", "3")
estimate <- c(0.3, 0.1, 0.5)
sig <- c("*", "ns", "*")
dt <- data.table(group1, group2, estimate, sig)

我正在尝试生成类似相关图的矩阵图。我不确定如何将 table 转换为以下内容。

     1     2     3
1    -     -     -
2   0.3    -     - 
3   0.1   0.5    -  

其中一个三角形的作用与另一个三角形的符号相反。

此外,我也想包括意义。

您可以使用 igraph 库中的函数:

library(igraph)
g <- graph.data.frame(dt, directed = FALSE)
get.adjacency(g, attr = "estimate", type = "lower")

3 x 3 sparse Matrix of class "dgCMatrix"
    1   2 3
1 .   .   .
2 0.3 .   .
3 0.1 0.5 .

我更喜欢@Maël 的解决方案,但这里有一个 data.table 方法

# build data.table
ans <- data.table(group1 = as.character(rep(1:3, 3)), 
                  group2 = as.character(rep(1:3, each = 3)))
# join data from dt
ans[dt, value := i.estimate, on = .(group1, group2)]

dcast(ans, group2 ~ group1, value.var = "value")
#    group2   1   2  3
# 1:      1  NA  NA NA
# 2:      2 0.3  NA NA
# 3:      3 0.1 0.5 NA