0

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
theo4786
  • 159
  • 1
  • 15
  • You wrote 3 column names in your File 1 whereas stated it has 4 columns. – Erdogan CEVHER Nov 23 '16 at 21:37
  • It will help if you reduce your code to reproducible example according to this: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Bulat Nov 23 '16 at 22:07
  • So you want to keep only those rows in file 2, which satisfy your condition, right? What is your desired output? – code_is_entropy Nov 23 '16 at 22:50

1 Answers1

0

I guess this is what you are looking for (it's a bit lengthy than I expected it to be)-

# First file as a data frame
df1 <- data.frame("Id"=c("ENSG00000210049","ENSG00000211459","ENSG00000210077"),
              "Chr"=c(1,1,1), "TSS"=c(63987904,63984904,58941831))

# Second file as a data frame
df2 <- data.frame("CHR"=c(1,1,1), "snps"=c("rs17125090","rs7546938","rs3087585"),
              "TES"=c(63988904,64677853,58971831))

# Join matching rows in second file
df2[c(names(df1),"diff")] <- data.frame(t(sapply(seq_along(df2$TES), function(x)
                        {
                        cbind(df1[which.min(abs(df2[x,"TES"] - df1[df1$Chr %in% df2[x,"CHR"], "TSS"])),],
                              min(abs(df2[x,"TES"] - df1[df1$Chr %in% df2[x,"CHR"], "TSS"])))
                        })))
code_is_entropy
  • 611
  • 3
  • 11