1
df1 <- data.frame(chrom = c("chr1","chr2", "chr5"), start=c(10,20,30), end = c(100,200,300), stringsAsFactors=FALSE)

df2 <- data.frame(chrom = c("chr1", "chr4", "chr2"),start=c(15,500,150), end = c(75,1000,300), stringsAsFactors=FALSE)

我的回答应该是:

chrom start  end
1  chr1    15   75

3  chr2   150  300

当我执行以下操作时:

for(i in 1:length(df2)){

for(j in 1:length(df1)){

if(df2$chrom[i] == df1$chrom[j])

    x <- df2[which(df1$chrom[j] == df2$chrom[i]),]

}
}

我得到:

chrom start end
1  chr1    15  75

显然我的逻辑是错误的。它只进行一次迭代。有人可以帮我理解吗?也许我不适合这种东西……无论如何,提前感谢您的帮助

4

1 回答 1

4

不确定 for 循环的用途,但也许这就是您所追求的?

df2[df2$chrom %in% df1$chrom, ]

编辑:进一步海报的理解:

> df2$chrom 
[1] "chr1" "chr4" "chr2"
> df2$chrom %in% df1$chrom
[1]  TRUE FALSE  TRUE
> df1$chrom
[1] "chr1" "chr2" "chr5"
于 2012-04-10T06:01:54.673 回答