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?

2 Answers 2

36

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]
1
1

Using dplyr:

M %>% select(col.order)

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

M %>% select(names(df))

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.