【问题标题】:Join rows in a data frame which have similar (but not equal) values连接数据框中具有相似(但不相等)值的行
【发布时间】:2017-11-18 09:59:36
【问题描述】:

我有一个df 喜欢:

   SampleID Chr Start End    Strand  Value
1:   rep1     1 11001 12000     -     10
2:   rep1     1 15000 20100     -     5
3:   rep2     1 11070 12050     -     1
4:   rep3     1 14950 20090     +     20
...

我想加入共享相同chrstrand 并且具有相似起点和终点的行(例如,100 +/- 距离)。对于执行行连接的那些列,我还想连接SampleID 名称和Value。在前面的示例中,类似于:

   SampleID Chr Start End    Strand  Value
1:rep1,rep2   1 11001 12000     -     10,1
2:   rep1     1 15000 20100     -     5
4:   rep3     1 14950 20090     +     20
...

想法?谢谢!

编辑:

我找到了 R 的模糊连接包 (https://cran.r-project.org/web/packages/fuzzyjoin/index.html)。有人有这个包的经验吗?

EDIT2:

如果只连接其中一个变量(SampleIDValue)也很好。

【问题讨论】:

    标签: r data.table fuzzyjoin


    【解决方案1】:

    我们可以通过'Chr'、'Strand'进行分组,根据ordering by 'Start'、'End'之后的'Start'和'End'列中相邻元素之间的差异创建一个分组ID,然后按'Chr'、'Strand'和'ind'分组,得到'Start'、'End'的第一个元素,同时pasteing'SampleID'和'Value'列中的元素

    library(data.table)
    df[order(Start, End), ind := rleid((Start - shift(Start, fill = Start[1])) < 100 & 
         (End -  shift(End, fill = End[1])) < 100), by =.(Chr, Strand)
       ][, .(Start = Start[1], End = End[1], 
         SampleID = toString(SampleID), Value = toString(Value)) , .(Strand, Chr, ind),]
    #     Strand Chr ind Start   End   SampleID Value
    #1:      -   1   1 11001 12000 rep1, rep2 10, 1
    #2:      -   1   2 15000 20100       rep1     5
    #3:      +   1   1 14950 20090       rep3    20
    

    注意:假设“df”是data.table

    【讨论】:

    • 哇!太好了,我想知道您是否可以对刚刚使用的命令更明确一点。如果我错了,请纠正我:您为每个条件生成一个“标签”,查看ChrStrandStartEnd,满足我提出的要求(+/- 100)。然后你加入了具有相同“标签”的那些,并将SampleIDValue 添加为字符串。我对吗?在我的data.table 中发生的另一件奇怪的事情是,完全相同位置的行不执行连接。问题出在哪里?
    • @Tato14 在第一组df[i, j, by] 中,我们指定iorder,以便这些值按升序排列。 by 是分组变量 'Chr', 'Strand',在'j'中,我们将逻辑输出的 run-length-id (rleid) 分配为新列,然后在第二组中,我们正在做一个分组操作。不清楚你什么时候说rows that are exactly at the sam position do not perform the join
    • 感谢您的解释!关于最后一部分,“位置”是指ChromStrandStartEnd
    • 我还在输出中发现了一些加入了SampleIDs 的行,它们与StartEnd 的条件不匹配,但得到相同的id。如果我只运行命令的第一部分,则会出现一条警告消息:RHS 1 is length 344 (greater than the size (32) of group 1). The last 312 element(s) will be discarded. RHS 1 is length 344 (greater than the size (5) of group 2)...
    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2018-06-20
    相关资源
    最近更新 更多