User981636
User981636

Reputation: 3621

Reorder matrix columns by matching column names to vector of names

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?

Upvotes: 17

Views: 28679

Answers (2)

Rentrop
Rentrop

Reputation: 21497

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]

Upvotes: 36

swarn
swarn

Reputation: 49

Using dplyr:

M %>% select(col.order)

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

M %>% select(names(df))

Upvotes: 2

Related Questions