我有以下数据:
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","chr1"),
start=c(15,500,150,200), end=c(75,1000,300,300), stringsAsFactors=FALSE)
我想做以下事情:
for(i in 1:nrow(df2)) {
# only if this condition is true (i.e. if there is overlap)
if((df1$start <= df2$start && df1$end >= df2$start) ||
(df1$start >= df2$start && df1$start <= df2$end)) {
x <- df2[which(df2$chrom %in% df1$chrom),]
}
}
答案应该是:
df3 <- data.frame(chrom=c("chr1", "chr2"), start=c(15,150),
end=c(75,300), stringsAsFactors=FALSE)
对不起所有的混乱。
人们对我的查询非常有耐心,这是一次非常有帮助和学习的经历。但是我试图了解循环是如何工作的,我越想越困惑。例如:
for(i in 1:nrow(df2)) {
x <- df2[which(df2$chrom %in% df1$chrom),]
}
与以下内容完全相同:
x <- df2[which(df2$chrom %in% df1$chrom),]
所以你甚至不需要循环。这怎么可能?我猜which
是在为你做循环吗?