11

Sorry if this is very basic. I have a list of names and a matrix with those names as column names. However, the colnames are in a different order.

Eg. List of names: colname4 colname3 colname2 colname5 colname1 Matrix Colnames: colname1 colname2 colname3 colname4 colname5

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

I have tried test <- match(colnames(matrix1), colnames(matrix2)) but it didn't work. Do you know any alternative?

user3507584
  • 2,881
  • 5
  • 36
  • 56

2 Answers2

28

You just have to use a vector for the names and the [-operator as follows:

col.order <- c("colname4","colname3","colname2","colname5","colname1")
M[,col.order]
Rentrop
  • 19,848
  • 8
  • 66
  • 97
  • 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
0

Using dplyr:

M %>% select(col.order)

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

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