2015-09-07 62 views
1

我有一个从data.frame创建的计数函数为R的表。它基本上是一行,其中行是染色体数目。但是,计数函数不会按染色体数量的顺序生成表格。如何解决这个问题。我尝试了排序和排序功能,但他们似乎并没有在桌子上工作。如何根据R中的col名对表进行排序?

dist<- read.table("~/Desktop/file.txt",header=TRUE,stringsAsFactors=FALSE) 
head(dist) 
Gene CHR ALLELE 
1 SLC35E2 1 C/T 
2  NADK 1 A/C 
3 TTC34 1 T/G 
4 PEX14 1 C/T 
5 TNFRSF1B 1 G/T 
6 CROCCP2 1 G/T 
uniq_dist<-dist[!duplicated(dist$Gene), ] 
dist_mat <- data.frame(uniq_dist[,-1], row.names= uniq_dist[,1]) 
counts <- table(dist_mat $CHR) 
counts 
1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 3 4 5 6 7 8 9 X 
21 12 18 16 7 15 11 4 14 4 16 20 4 4 2 23 9 10 8 12 3 12 5 
dim(counts) 
[1] 23 
class(counts) 
"table" 
I want to arrange the order of in the chromosome number from 1-22 and then X at the end and then plot using bar plot 

So the desired output should be in order of 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 X 
21 20 23 9 10 8 12 3 12 12 18 16 7 15 11 4 14 4 16 4 4 2 5 

我怎么能做到这一点,我知道在数据帧做的,但在表中没有没有,我想知道这一点。由于

+0

可以转换为'factor'指定为'该列的unique'值水平,然后后做'table'即'$ dist_mat CHR < - 因子( dist_mat $ CHR,levels = c(1:22,'X'))' – akrun

+1

如果你提供一个可重复的例子,但我认为'count [order(as.numeric(names(counts)))]'' 。 – Frank

+0

感谢截至目前,它适用于此,同时警告NA介绍,但它给了我所需的输出,我可以绘制它。谢谢 –

回答

2

如果“CHR”栏目为ordered,我们可以将列转换为factor指定为“CHR”的unique价值levels,然后做table

table(with(dist_mat, factor(CHR, levels= unique(CHR)))) 

如果没有有序的,我们可以指定levels在我们希望它出现在table

table(with(dist_mat, factor(CHR, levels= c(1:22, 'X')))) 

使用重复的例子

set.seed(24) 
v1 <- sample(c(1:22, 'X'), 100, replace=TRUE) 
order

OP的方法

table(v1) 
# v1 
# 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 3 4 5 6 7 8 9 X 
#2 3 5 6 3 4 4 4 7 3 2 5 2 2 4 5 6 4 8 5 6 6 4 

转换为factor

table(factor(v1, levels=c(1:22, 'X'))) 
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 X  
# 2 5 5 6 4 8 5 6 6 3 5 6 3 4 4 4 7 3 2 2 2 4 4 
+0

它也可以工作,非常感谢,我已经做了,并且也创建了这些情节,我其实并没有这样想。非常感谢 –

+1

它被接受。 –

相关问题