如何对列进行排序,使其与不同数据框中的行顺序匹配?

时间:2017-05-05 07:16:44

标签: r sorting

感谢堆栈,我能够对这个数据帧进行排序,首先是根据“状态”,然后是“ID”,它看起来像:

>pheno
  ID             status
1 patient19      0
2 patient21      0
3  patient7      1
4 patient10      1

(制作现象的代码):

ID = c("patient19", "patient21", "patient7", "patient10")
pheno = as.data.frame(ID)
pheno$status = c("0", "0", "1", "1")
row.names(phenodf) = pheno$ID

但现在我有了第二个数据框,其中ID现在是列标题,需要对它们进行排序,使其与pheno df中的顺序相匹配。我怎么能这样做?

>genes
gene     patient7 patient21 patient19 patient10
ABC      1.5       2.3       3.3       4.4
A2B      2.5       1.3       3.1       2.3
DE5      3.5       3.3       3.4       1.4
ZXY      4.5       4.3       3.6       5.1

(制作基因df的代码):

patient7 = c(1.5, 2.5, 3.5, 4.5)
genes = as.data.frame(patient7)
genes$patient21 = c(2.3, 1.3, 3.3, 4.3)
genes$patient19 = c(3.3, 3.1, 3.4, 3.6)
genes$patient10 = c(4.4, 2.3, 1.4, 5.1)
row.names(genes) = c("ABC", "A2B", "DE5", "ZXY")

这就是我需要基因df的样子:

genes     patient19 patient21 patient7 patient10
ABC       3.3       2.3      1.5       4.4
A2B       3.1       1.3      2.5       2.3
DE5       3.4       3.3      3.5       1.4
ZXY       3.6       4.3      4.5       5.1

1 个答案:

答案 0 :(得分:0)

您可以使用match执行此操作,第一个参数是您要重新排序的标签,第二个参数是所需的顺序:

genes[, match(colnames(genes), rownames(pheno))]

仅执行match的结果是:

3 2 1 4

这就是您需要genes数据框的列的顺序,与pheno数据框中的顺序相关。

相关问题