17

I have a matrix with column names and a vector of names in a different order.

Matrix column names:

c("colname1", "colname2", "colname3", "colname4", "colname5")

Vector of names:

c("colname4", "colname3", "colname2", "colname5", "colname1")

I am trying to order the matrix columns in the same order as the names in the vector.

I have tried:

test <- match(colnames(matrix1), colnames(matrix2))`

but it didn't work. Do you know any alternative?

Henrik
  • 65,555
  • 14
  • 143
  • 159
user3507584
  • 3,246
  • 5
  • 42
  • 66

2 Answers2

35

Index the matrix with the [-operator and the vector of column names in the desired order:

col.order <- c("colname4","colname3","colname2","colname5","colname1")
    M[ , col.order]
Henrik
  • 65,555
  • 14
  • 143
  • 159
Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • 2
    If it is a `data.table`, you can use [the .. undocumented feature](https://stackoverflow.com/a/45381491/1048186): `M[ , ..col.order]` – Josiah Yoder Jun 26 '20 at 19:07
1

Using dplyr:

M %>% select(col.order)

If you want arrange the columns order based on another data frame:

M %>% select(names(df))
swarn
  • 39
  • 4