How to create a correlation matrix of p values from the output of a dunns test?

294 views Asked by At

Using the following data frame, I need to do a dunn_test to see which Locs are different from one another according to each var:

set.seed(123)
dat1 <- data.frame(Loc = rep(letters[1:20], each = 10),
                   ID = 1:200,
                   var1 = rnorm(200),
                   var2 = rnorm(200),
                   var3 = rnorm(200),
                   var4 = rnorm(200),
                   var5 = rnorm(200),
                   var6 = rnorm(200))
dat1$ID <- factor(dat1$ID)
library(rstatix)
res <- dunn_test(dat1, var1 ~ Loc)

How can I make a "correlation matrix of p values" between the Locs from the object res, so that it will look like the following, and show the p values for each pairwise comparison:

 a b c d e f g h i j k l m n o p q r s t
a 
b 
c 
d 
e 
f 
g 
h 
i 
j 
k 
l 
m 
n 
o 
p 
q 
r 
s 
t
2

There are 2 answers

2
dcarlson On BEST ANSWER

Here is a base R approach:

pvals <- res$p
dst <- matrix(NA, 20, 20)
dst[lower.tri(dst)] <- pvals
dst <- as.dist(dst)
attr(dst, "Labels") <- letters[1:20]
dst <- as.matrix(dst, upper=TRUE, lower=TRUE)
dst[1:5, 1:5]
#           a          b          c          d         e
# a 0.0000000 0.54159206 0.25928005 0.33606421 0.7661024
# b 0.5415921 0.00000000 0.08212246 0.72516551 0.3639394
# c 0.2592800 0.08212246 0.00000000 0.03661193 0.4061898
# d 0.3360642 0.72516551 0.03661193 0.00000000 0.2078686
# e 0.7661024 0.36393940 0.40618977 0.20786861 0.0000000

You did not indicate what you wanted in the diagonal. Since these are p values, it would make sense to fill the diagonal with 1's:

diag(dst) <- 1
4
Limey On

As requested:

data.frame(Group1=res$group1, Group2=res$group2, PValue=res$p) %>% 
  group_by(Group2) %>% 
  pivot_wider(values_from="PValue", names_from=c("Group1"))

Gives you a lower triangular matrix of unadjusted p-values. Swapping Group2 and "Group1" (in the group_by and pivot_wider verbs) will give you an upper triangular matrix.