How to reorder the rows and columns of a correlation matrix created within a function

Viewed 1072

Consider the following data frame dat1:

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

The following function will use the rstatix package to do a dunn_test between the levels of Loc for whichever var is specified, and it will return a correlation matrix of the p values from the dunn_test:

library(rstatix)
dunn.cor <- function(dat, var, gv){
  res <- dat%>% rstatix::dunn_test(as.formula(paste(var, "~", gv)))
  p <- res$p
 dst <- matrix(NA, 20, 20)
 dst[lower.tri(dst)] <- p
 dst <- as.dist(dst)
 attr(dst, "Labels") <- levels(dat1$Loc)
 dst <- as.matrix(dst, upper=TRUE, lower=TRUE)
 diag(dst) <- 1
 dst <- round(dst,2)
 return(dst)
}
#example for var1:
dunn.cor(dat=dat1, var= "var1", gv = "Loc")

I would like to create an object order outside of the function that specifies the order that I want the rows AND columns to appear in the matrix. for example:

order <- c("m", "l", "n", "h", "p", "j", "r", "k", "c", "d", "f", "o", "t", "i", "g", "s", "e", "q", "b", "a")

To clarify, I want the rows AND the columns of the matrix to be in this order, just like a regular correlation matrix. How can I modify the function so that the matrix rows and columns will be in this order?

1 Answers

If we need to have this in a specific order, may be create a factor with levels specified

dat1$Loc <- factor(dat1$Loc, levels = order)

and then we apply

library(dplyr)
library(tidyr)
library(tibble)
out <- dat1 %>% 
   rstatix::dunn_test(var1 ~ Loc) %>%
   select(group1, group2, p) %>%
   pivot_wider(names_from = group2, values_from = p, values_fill = list(p = 0)) %>% 
   column_to_rownames('group1') %>% 
   as.matrix
out1 <- out + t(out)



dimnames(out1)
#[[1]]
# [1] "m" "l" "n" "h" "p" "j" "r" "k" "c" "d" "f" "o" "t" "i" "g" "s" "e" "q" "b"

#[[2]]
# [1] "l" "n" "h" "p" "j" "r" "k" "c" "d" "f" "o" "t" "i" "g" "s" "e" "q" "b" "a"

If we need a binary matrix

out2 <- +(out1 <= 0.05)

and plot with corrplot

corrplot(out2, is.corr = FALSE, type = 'lower')
Related