I have two files. File 1 has 56632 rows and 4 columns, and looks like:
Id Chr TSS TES
ENSG00000210049 1 63987904 63989904
ENSG00000211459 1 63984904 63985904
ENSG00000210077 1 58941831 58991831
And file 2 has 28895 rows and 3 columns, and looks like:
CHR snps POS
1 rs17125090 63988904
1 rs7546938 64677853
1 rs3087585 58971831
I am trying to run a nested for loop in order to find, for every row in file 2, the row in file 1 which has the value in field 3 that is closest to the value in field 3 from file 2, given that field 2 from file 1 and field 1 from file 2 are matching. My code is:
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)
I'm getting the error Error in pi[[j]] : subscript out of bounds
for the line df<-rbind.data.frame(df,i.df2)
. Can someone point out what's going wrong?
Desired output:
1 rs17125090 63988904 ENSG00000210049 1 63987904 1000
1 rs7546938 64677853 ENSG00000210049 1 63987904 689949
1 rs3087585 58971831 ENSG00000210077 1 58941831 30000