1

If I have a martix that looks like this:

Name <- list("A","B","C", "D")

mat <- matrix(1:4, ncol = 4)
colnames(mat) <- Name
mat

which produces:

     A B C D
[1,] 1 2 3 4

And I have a vector like the:

nameOrder <- c("B","D","A","C")

Is there a way to reorder the matrix columns so that the order matches that of the vector nameOrder? That is, the result would look something like this:

mat_1 <- reorder(mat columns to = nameOrder)
mat_1

    B D A C 
[1,]2 4 1 3
Electrino
  • 2,636
  • 3
  • 18
  • 40

1 Answers1

2

We can just as the 'nameOrder' as column names

mat[, nameOrder, drop = FALSE]
akrun
  • 874,273
  • 37
  • 540
  • 662