Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Reorder matrix columns by matching colnames to list of string

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?

like image 218
user3507584 Avatar asked Aug 22 '14 12:08

user3507584


1 Answers

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]
like image 139
Rentrop Avatar answered Oct 31 '22 12:10

Rentrop