使用for循环

时间:2012-04-10 05:41:56

标签: r

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
显然我的逻辑错了。它只进行一次迭代。有人可以帮我理解吗?也许我不是为这种东西而做的......反正感谢你的帮助

1 个答案:

答案 0 :(得分: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"