R通过将列名匹配到字符串列表来对矩阵列重新排序 [英] R Reorder matrix columns by matching colnames to list of string

查看:164
本文介绍了R通过将列名匹配到字符串列表来对矩阵列重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果这是非常基本的. 我有一个名称列表和一个以这些名称作为列名称的矩阵.但是,姓氏的顺序不同.

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.

例如.名称列表:colname4 colname3 colname2 colname5 colname1 矩阵姓氏:colname1 colname2 colname3 colname4 colname5

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.

我尝试了test <- match(colnames(matrix1), colnames(matrix2)),但没有成功.你知道其他办法吗?

I have tried test <- match(colnames(matrix1), colnames(matrix2)) but it didn't work. Do you know any alternative?

推荐答案

您只需使用向量来命名名称和[-运算符,如下所示:

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]

这篇关于R通过将列名匹配到字符串列表来对矩阵列重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆