首页 > 解决方案 > 将具有共同值的行放入列表中

问题描述

我正在尝试根据“区域类型”列中的值将行放入列表中,并将这些列表放入其他数据结构(向量或列表)中。数据看起来像这样(~700 000 行):

chr CS  CE  CloneName   score   strand  # locs per clone    # capReg alignments Type of region  
chr1    10027684    10028042    clone_11546 1   +   1   1   chr1_10027880_10028380_DNaseI
chr1    10027799    10028157    clone_11547 1   +   1   1   chr1_10027880_10028380_DNaseI
chr1    10027823    10028181    clone_11548 1   -   1   1   chr1_10027880_10028380_DNaseI
chr1    10027841    10028199    clone_11549 1   +   1   1   chr1_10027880_10028380_DNaseI

这是我试图做的:

typeReg=dat[!duplicated(dat$`Type of region`),]

for(i in 1:nrow(typeReg)){
    res[[i]]=dat[dat$`Type of region`==typeReg[i,]$`Type of region`,]
}

for 循环花费了太多时间,所以我尝试使用 apply:

res=apply(typeReg, 1, function(x){
    tmp=dat[dat$`Type of region`==x[9],]
})

但它也很长(区域类型列中有 300 000 个唯一值)。您对我的问题有解决方案吗,或者需要这么长时间是正常的吗?

标签: rbioinformatics

解决方案


您可以使用split()

type <- as.factor(dat$Type_of_Region)
split(dat, type)

但是,正如评论中所述,使用dplyr::group_by()可能是更好的选择,具体取决于您以后想要做什么。


推荐阅读