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?