繁体   English   中英

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

[英]How do I sort my columns so that they match the order of rows in a different dataframe?

多亏了堆栈,我能够首先根据“状态”然后按“ ID”对数据框进行排序,如下所示:

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

(使pheno df的代码):

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

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

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

仅执行match的结果是:

3 2 1 4

相对于pheno数据pheno的顺序,这只是您需要genes数据pheno的列的顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM