染色体坐标排序的两个方法

绘图的时候经常会遇到这个问题,有些NGS软件也会遇到。使用下面的代码模拟数据

pos_df=do.call(rbind,lapply(1:10, function(i){
 data.frame(gene=paste0('gene',i,LETTERS),
 chr=sample(paste0('chr',1:22),26,replace = T),
 start= sample(1:1000,26))
}))
pos_df=pos_df[with(pos_df,order(chr,start)),]
pos_df$chr=as.factor(pos_df$chr)
plot(pos_df$chr,pos_df$start,las=2)

首先我们的排序并没有按照染色体顺序,而是

> levels((pos_df$chr))
 [1] "chr1" "chr10" "chr11" "chr12" "chr13" "chr14" "chr15" "chr16"
 [9] "chr17" "chr18" "chr19" "chr2" "chr20" "chr21" "chr22" "chr3" 
[17] "chr4" "chr5" "chr6" "chr7" "chr8" "chr9" 
>

这种情况下sort这个向量其实是没有意义的, 有两个方案可以解决它!

首先是设置因子的水平即可,代码如下:

pos_df$chr=factor(pos_df$chr,paste0('chr',1:22),ordered = T)
pos_df=pos_df[with(pos_df,order(chr,start)),]
plot(pos_df$chr,pos_df$start,las=2)

第二个方案是可以通过在数字前面补0来

 pos_df$chr = paste('chr',
 sprintf('%02d',as.numeric(gsub('chr','',pos_df$chr))) ,
 sep = '') 
 pos_df$chr = as.factor((pos_df$chr))

修改后再次查看其因子的水平 如下:

> levels((pos_df$chr))
 [1] "chr01" "chr02" "chr03" "chr04" "chr05" "chr06" "chr07" "chr08" "chr09"
[10] "chr10" "chr11" "chr12" "chr13" "chr14" "chr15" "chr16" "chr17" "chr18"
[19] "chr19" "chr20" "chr21" "chr22"

如果有X,Y染色体,可以转换为数值,比如 第24,25,26号染色体分别是X,Y,MT染色体。

Comments are closed.