Merge by Range in R - Applying Loops

前端 未结 3 1072
失恋的感觉
失恋的感觉 2020-11-28 12:59

I posted a question here: Matched Range Merge in R about merging two files based on a number in one file falling into a range in the second file. Thus far, I have been unsuc

3条回答
  •  心在旅途
    2020-11-28 13:42

    You can merge by range in base by using apply and which. To return only those which match (inner join):

    do.call(rbind, apply(file1test, 1, function(x) {
      if(length(idx <- which(x["BP"] >= file2$BP_start & x["BP"] <= file2$BP_end)) > 0) {
        cbind(rbind(x), file2[idx,])
      }
    }))
    #      SNP     BP  Gene BP_start BP_end
    #x  rs2343 860269 E3543   860260 879955
    #1   rs754 861822 E3543   860260 879955
    #2   rs754 861822   E11   861322 879533
    #x1  rs854 367934  E613   367640 368634
    

    or all from file1test (left join):

    do.call(rbind, apply(file1test, 1, function(x) {
      if(length(idx <- which(x["BP"] >= file2$BP_start & x["BP"] <= file2$BP_end)) > 0) {
        cbind(rbind(x), file2[idx,])
      } else {
        cbind(rbind(x), file2[1,][NA,])
      }
    }))
    #      SNP     BP  Gene BP_start BP_end
    #x  rs2343 860269 E3543   860260 879955
    #x1  rs211 369640         NA     NA
    #1   rs754 861822 E3543   860260 879955
    #2   rs754 861822   E11   861322 879533
    #x2  rs854 367934  E613   367640 368634
    #x3  rs343 706940         NA     NA
    #x4  rs626 717244         NA     NA
    

提交回复
热议问题