2

我有一个染色体名称向量

q<-c("1","10","11","12","13","14","15","16","17",
     "18","19","20","21","22","2","3","4","5","6",
     "7","8","9","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")

我试着自己下订单

chrOrder <-c((1:22),"X","Y","M")

并像使用它一样

factor(cbind(q),levels=chrOrder)

但我仍然无法得到它。

已编辑.....我有类似的情况,但有点先进。我有一个三列的数据框,名称,染色体,开始

df <-data.frame(name =c("a","a","a","b","b","b"), chrom = c(1,2,10,1,3,"X"), start=c(100,200,300,500,300,200))

我需要先按名称排序,然后是染色体和开头。结果应该是这样的

name chrom start
a     1   100
a     10  300
a     2   200
b     1   500
b     3   300
b     X   200

我不知道如何在以下使用 chrOrder:

indata  <- df[do.call(order,df[,c(name, chrom, start)]),];
4

2 回答 2

3

你的方法很好;你只需要sort结果因子。您还应该设置ordered=TRUE

sort(factor(q,levels=chrOrder, ordered=TRUE))

不,您不必使用有序因子,正如已经指出的那样,但这肯定没有错——而且可以说它更好。因素适用于这种情况,您有明确定义的水平。请参阅上一个关于factorvscharacter的问题。

现在你已经编辑了你的问题,因为排序很简单,所以一个因素的情况更加强大:

df <- data.frame(name=c("a","a","a","b","b","b"),
                 chrom = c(1,2,10,1,3,"X"),
                 start=c(100,200,300,500,300,200))

chrOrder <-c((1:22),"X","Y","M")
df$chrom <- factor(df$chrom, chrOrder, ordered=TRUE)

df[do.call(order, df[, c("name", "chrom", "start")]), ]

给定因子的级别,R 确切地知道如何对元素进行排序。

我已经按照您的排序方法进行了引导,但您可能想知道还有更漂亮的方法,例如:

library(plyr)
df <- arrange(df, name, chrom, start)
于 2013-09-25T20:29:26.890 回答
3

factor并且cbind不要在这里做任何事情(嗯,factor确实如此,但它不会立即有用)。

在您的具体情况下,只是说q <- chrOrder解决了问题,不是吗?

更一般地,您可以使用match获取x由另一个向量中的项目排序的向量中项目的索引y

> match(chrOrder, q)
 [1]  1 15 16 17 18 19 20 21 22  2  3  4  5  6  7  8  9 10 11 12 13 14 23 24 25

现在您可以使用这些索引来索引q并对其进行排序:

> q[match(chrOrder, q)]
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15"
[16] "16" "17" "18" "19" "20" "21" "22" "X"  "Y"  "M"

......所以这是一般的方法。例如,作为一个更有用的示例:假设您实际上有一个data.frame带有一列的基因chr,您可以按如下方式对数据框的行进行排序:

> # Some test data
> df <- data.frame(chr = q, value = rnbinom(length(q), 1, 0.01),
+                  row.names = paste('gene', seq_along(q)))
> df <- df[match(chrOrder, df$chr), ]
> head(df)
        chr value
gene 1    1   270
gene 15   2    51
gene 16   3   115
gene 17   4    15
gene 18   5   196
gene 19   6    34

…数据框列现在chr按您想要的顺序按其列排序。

于 2013-09-25T20:34:10.740 回答