R中for循环后的rbind错误

时间:2016-11-23 21:33:00

标签: r for-loop rbind

我有两个文件。文件1有56632行和4列,看起来像:

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 

我正在尝试运行嵌套for循环,以便为文件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

1 个答案:

答案 0 :(得分:0)

我想这就是你要找的东西(它比我预期的要长一点) -

# 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"])))
                        })))