按给定顺序排序,然后对其余部分进行排序

时间:2013-12-24 15:16:33

标签: r sorting

我有

q<-c("1","10","11","12","13","14","15","16","17",
 "18","19","20","21","22","GL000205.1","GL000205.2","2","3","4","5","6",
 "7","8","9","GL000205.1","X","Y","M")

我想将它们排序为

q<-c("1","2","3","4","5","6","7","8","9","10","11",
 "12","13","14","15","16","17","18","19","20",
 "21","22","X","Y","M","GL000205.1","GL000205.2")

我用过

chrOrder <-c((1:22),"X","Y","M")
indata[,chrom.pos]<- factor(indata[,chrom.pos], chrOrder,ordered=TRUE)

这会对数据进行排序,但会将GL000205.1和GL000205.2变为空白。我想恢复所有内容并按照chr1,2,3 ,, ....顺序对它们进行排序。我采取了上述方法,因为我知道chr 1,2 ,, .... Y,M在手之前。我没有关于其他染色体的信息。 如果我不必事先提供任何订单(chrOrder)会更有效率,因为在那种情况下不会丢失任何信息。 我想在chrmOrder的末尾添加一些外卡,这样可以将染色体的其余部分放在最后。

EDITED: 如果我有q

q<-c("1","10","11","12","13","14","15","16","17",
 "18","19","20","21","22","GL000205.1","GL000205.2","2","3","4","5","6",
 "7","8","9","GL000205.1","23","24","25")

给定的解决方案可以正常工作,但也会返回“X”,“Y”,“M”。 是否有可能按“q”中的顺序排序,不要返回“X”,“Y”“M”?

2 个答案:

答案 0 :(得分:1)

我不确定我是否理解正确,但为什么不将chrOrder定义如下?

chrOrder <-c((1:22),"X","Y","M")
chrOrder <-c(chrOrder,sort(unique(q[!q %in% chrOrder])))

答案 1 :(得分:1)

如果您只想要q中出现的那些1:22,X,Y和M成为关卡的一部分,您可以将chrOrder定义为

chrOrder <-intersect(c((1:22),"X","Y","M"),q)
chrOrder <-c(chrOrder,sort(setdiff(q, chrOrder)))

第二行相当于Codoremifa答案的第二行;第一个只保留集合[1:22,X,Y,M]中同样位于q的部分。