Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Last active March 30, 2019 10:03
Show Gist options
  • Save nilforooshan/e63cd36dccd14ea920f4a8c4d2bd3d49 to your computer and use it in GitHub Desktop.
Save nilforooshan/e63cd36dccd14ea920f4a8c4d2bd3d49 to your computer and use it in GitHub Desktop.
R: Re-order a square matrix

R function for re-ordering a square matrix

The function:

SQmat_reorder <- function(inpmat, oldorder, neworder) # Input matrix (inpmat), oldorder & neworder inputs
{
   colnames(inpmat) = row.names(inpmat) = oldorder
   outmat <- inpmat[match(neworder, oldorder), match(neworder, oldorder)]
   return(outmat)
}

Example:

(mymatr <- matrix(1:16,nrow=4,ncol=4,byrow=TRUE))

Input:

     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
[4,]   13   14   15   16
oldord <- c("CAN", "DEU", "FIN", "FRA")
neword <- c("DEU", "FRA", "FIN", "CAN")
SQmat_reorder(mymatr, oldord, neword)

Output:

    DEU FRA FIN CAN
DEU   6   8   7   5
FRA  14  16  15  13
FIN  10  12  11   9
CAN   2   4   3   1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment