我有两个文件。文件1有56632行4列,看起来像:r循环后出现rbind错误
Id Chr TSS TES
ENSG00000210049 1 63987904 63989904
ENSG00000211459 1 63984904 63985904
ENSG00000210077 1 58941831 58991831
和文件2有28895行3列,看起来像:
CHR snps POS
1 rs17125090 63988904
1 rs7546938 64677853
1 rs3087585 58971831
我想运行一个嵌套的循环为了为文件2中的每一行查找文件1中具有字段3中值最接近文件2中字段3中值的行,假定文件1中的字段2和文件2中的字段1正在匹配。我的代码是:
genes<-read.table("file1",header=T)
snps<-read.table("file2",header=T)
df<-data.frame()
for(i in 1:10){
i.genes<-data.frame()
i.dist<-data.frame()
for(j in 1:56632){
if((snps[i,1]==genes[j,2]) & (abs(snps[i,3]-genes[j,3])<2000000)){
i.genes<-rbind(i.genes,genes[j,1:3])
i.dist<-rbind(i.dist,abs(genes[j,3]-snps[i,3]))
i.df<-cbind(i.genes,i.dist)
}
}
i.df<-i.df[order(i.df[,4]),]
i.df<-i.df[1,]
i.df2<-cbind(snps[i,1:3],i.df)
colnames(i.df2)<-NULL
df<-rbind.data.frame(df,i.df2)
}
write.table(df,"test.df",quote=F,row.names=F)
,我发现了错误Error in pi[[j]] : subscript out of bounds
为线df<-rbind.data.frame(df,i.df2)
。有人能指出哪里出了问题吗?
所需的输出:
1 rs17125090 63988904 ENSG00000210049 1 63987904 1000
1 rs7546938 64677853 ENSG00000210049 1 63987904 689949
1 rs3087585 58971831 ENSG00000210077 1 58941831 30000
你在你的文件中写道3个名1表示它有4列。 –
这将有助于如果你减少你的代码重现性的例子根据这个:http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Bulat
所以,你想只保留文件2中的那些行满足您的条件,对吗?你想要的输出是什么? –