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.
CodePudding user response:
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 .
CodePudding user response:
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