R Reorder matrix columns by matching colnames to list of string

ε祈祈猫儿з 提交于 2020-03-14 06:56:44

问题


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?


回答1:


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]


来源:https://stackoverflow.com/questions/25446714/r-reorder-matrix-columns-by-matching-colnames-to-list-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!