简体   繁体   中英

Converting a table to a correlation type matrix

I have the results of a post-hoc analysis. I want to convert it to a correlation type matrix

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)

I'm trying to generate a matrix plot like a correlation plot. I'm not sure how to transform the table into the following.

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

One of the triangles will do as the other will have opposite signs.

Additionally, I would like to include the significance as well.

You can use functions from the igraph library:

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 .

I prefer @Maël's solution, but here is a data.table approach

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM