title: How to reorder the rows and columns of a correlation matrix created within a function
body: <p>Consider the following data frame <code>dat1</code>:</p>
  <pre class="lang-r prettyprint-override"><code>set.seed(123)
  dat1 &lt;- 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 &lt;- factor(dat1$ID)
  </code></pre>
  <p>The following function will use the <code>rstatix</code> package to do a <code>dunn_test</code> between the levels of <code>Loc</code> for whichever <code>var</code> is specified, and it will return a correlation matrix of the p values from the <code>dunn_test</code>:</p>
  <pre class="lang-r prettyprint-override"><code>library(rstatix)
  dunn.cor &lt;- function(dat, var, gv){
    res &lt;- dat%&gt;% rstatix::dunn_test(as.formula(paste(var, &quot;~&quot;, gv)))
    p &lt;- res$p
   dst &lt;- matrix(NA, 20, 20)
   dst[lower.tri(dst)] &lt;- p
   dst &lt;- as.dist(dst)
   attr(dst, &quot;Labels&quot;) &lt;- levels(dat1$Loc)
   dst &lt;- as.matrix(dst, upper=TRUE, lower=TRUE)
   diag(dst) &lt;- 1
   dst &lt;- round(dst,2)
   return(dst)
  }
  #example for var1:
  dunn.cor(dat=dat1, var= &quot;var1&quot;, gv = &quot;Loc&quot;)
  </code></pre>
  <p>I would like to create an object <code>order</code> outside of the function that specifies the order that I want the rows AND columns to appear in the matrix.
  for example:</p>
  <pre class="lang-r prettyprint-override"><code>order &lt;- c(&quot;m&quot;, &quot;l&quot;, &quot;n&quot;, &quot;h&quot;, &quot;p&quot;, &quot;j&quot;, &quot;r&quot;, &quot;k&quot;, &quot;c&quot;, &quot;d&quot;, &quot;f&quot;, &quot;o&quot;, &quot;t&quot;, &quot;i&quot;, &quot;g&quot;, &quot;s&quot;, &quot;e&quot;, &quot;q&quot;, &quot;b&quot;, &quot;a&quot;)
  </code></pre>
  <p>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?</p>