我有兩個文件。文件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中的那些行滿足您的條件,對嗎?你想要的輸出是什麼? –