10
votes

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?

2

2 Answers

26
votes

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]
0
votes

Using dplyr:

M %>% select(col.order)

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

M %>% select(names(df))