【问题标题】:merge two data.frame with condition in R合并两个data.frame与R中的条件
【发布时间】:2015-07-11 13:33:18
【问题描述】:

我想比较两个数据集 df1df2,这样,df2$ID 中的唯一字符应作为新列添加到 df1 并为每个数据集分配 df2$Xp 值基因,如果df1的坐标与df2的坐标重叠:

 df1 <- read.table(text="
        Gene     chr  Start End 
        Gm12724   4  1000   1105    
        Zfhx2     4  1254   1369    
        Usp17lc   7  5004   5412
        Lingo1    7  5698   5789
        Sart3     7  5987   6041
        Olfr978   4  1452   1564
    ", header=T)


    df2 <- read.table(text="
        ID      chr Start   End     Xp
        S8411     4  989    1258   0.312
        S8411     4  1300   1800   0.144
        S8411     7  5641   6874   0.136
        S8413     4  1307   1360  -1.999
",header=T)

预期输出

 df3 <- read.table(" 
        Gene    chr   Start End   S8411  S8413
        Gm12724   4  1000   1105  0.312     0
        Zfhx2     4  1294   1369  0.144     -1.999
        Usp17lc   7  5004   5412    0       0
        Lingo1    7  5698   5789  0.136     0
        Sart3     7  5987   6041  0.136     0
        Olfr978   4  1452   1564   0.144    0
",header=T)

【问题讨论】:

  • @akrun。我知道 findOverlaps 给出了重叠区域。从那我如何通过在 df1 中添加 unique(df2$ID) 作为新列来创建新数据集

标签: r bioinformatics bioconductor


【解决方案1】:

这可能有帮助

library(data.table)
setkey(setDT(df1),chr, Start, End)
setkey(setDT(df2), chr, Start, End)
res <- foverlaps(df1, df2,  type='any')[
   ( Start > i.Start| End> i.End)|is.na(Start)][,
   c('Start', 'End') := list(i.Start, i.End)][,7:8 := NULL]
dcast(res, ...~ID, value.var='Xp', fill=0)[, -7, with=FALSE]
#    chr Start  End    Gene S8411  S8413
#1:   4  1000 1105 Gm12724 0.312  0.000
#2:   4  1254 1369   Zfhx2 0.144 -1.999
#3:   4  1452 1564 Olfr978 0.144  0.000
#4:   7  5004 5412 Usp17lc 0.000  0.000
#5:   7  5698 5789  Lingo1 0.136  0.000
#6:   7  5987 6041   Sart3 0.136  0.000

【讨论】:

  • akrun@ 收到错误消息:重叠连接中不允许重复列。这可能会在未来发生变化。
  • @beginner 根据您提供的示例,我没有收到任何错误。另请检查基因组范围解决方案是否适合您stackoverflow.com/questions/29648127/…
  • 它适用于示例。但是当我用我的原始数据集尝试它时,它得到了错误。
  • @beginner 如果没有给出错误的示例,我不确定问题出在哪里。您可以尝试链接中的解决方案吗?
  • 该链接没有为我的查询提供解决方案。
猜你喜欢
  • 2016-08-01
  • 1970-01-01
  • 2015-07-29
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 2013-01-24
  • 2018-02-18
  • 1970-01-01
相关资源
最近更新 更多