【问题标题】:How to keep join column unchanged in data.table non-equi join?如何在 data.table 非等连接中保持连接列不变?
【发布时间】:2017-11-12 09:46:32
【问题描述】:

我试图使用data.table 的非等连接功能删除data.frame 中的行,其中posn 列中的值不在另一个data.frame 中给出的范围内。

我的数据如下所示:

library(data.table)
df.cov <-
    structure(list(posn = c(1, 2, 3, 165, 1000), att = c("a", "b",
    "c", "d", "e")), .Names = c("posn", "att"), row.names = c(NA,
    -5L), class = "data.frame")
df.exons <-
    structure(list(start = c(2889, 2161, 277, 164, 1), end = c(3329,
    2826, 662, 662, 168)), .Names = c("start", "end"), row.names = c(NA,
    -5L), class = "data.frame")

setDT(df.cov)
setDT(df.exons)

df.cov
#    posn att
# 1:    1   a
# 2:    2   b
# 3:    3   c
# 4:  165   d
# 5: 1000   e
df.exons # ranges of `posn` to include
#    start  end
# 1:  2889 3329
# 2:  2161 2826
# 3:   277  662
# 4:   164  662
# 5:     1  168

这是我尝试过的:

df.cov[df.exons, on = .(posn >= start, posn <= end), nomatch = 0]
#    posn att posn.1
# 1:  164   d    662
# 2:    1   a    168
# 3:    1   b    168
# 4:    1   c    168
# 5:    1   d    168

可以看到df.cov中的posn列也发生了变化。预期结果如下所示:

#    posn att
# 1:  165   d
# 2:    1   a
# 3:    2   b
# 4:    3   c
# 5   165   d
# the row order doesn't matter. I'll sort by posn latter.
# It is also fine if the duplicated rows are removed, otherwise I'll do this in next step.

如何使用data.table non-equi join 获得所需的输出?

【问题讨论】:

  • df.cov[df.cov[df.exons, on = .(posn &gt;= start, posn &lt;= end), nomatch = 0, which=TRUE]] 我已经为这种子集github.com/Rdatatable/data.table/issues/2158 提交了一份 FR(不过不确定是否有意义,因为还没有人回复它)。要删除欺骗,只需在子集之前将unique 应用于which 向量。
  • @Frank,谢谢。这是我根据你的最终得出的结论:df.cov[sort(unique(df.cov[df.exons, on = .(posn &gt;= start, posn &lt;= end), nomatch = 0, which=TRUE]))]。我阅读了您的 FR,我认为这样的功能在很多情况下都会很有帮助。
  • @akrun,感谢您提供有用的链接,讨论 between 和 inrange 之间的区别。
  • 还有this

标签: r data.table


【解决方案1】:

你也可以使用%inrange%:

df.cov[posn %inrange% df.exons]

导致:

   posn att
1:    1   a
2:    2   b
3:    3   c
4:  165   d

如您所见,posn 列的值保持不变。


另一种可能,虽然更长:

df.exons[df.cov
         , on = .(start <= posn, end >= posn)
         , mult ='first'
         , nomatch = 0
         , .(posn = i.posn, att)][]

【讨论】:

  • 如此简单。我以前从未注意到这个秘密功能。
  • @mt1022 添加了另一个选项
  • 我没想到你会花时间找到一个完全符合我在帖子中要求的解决方案。非常感谢“non-equi join”方法。
猜你喜欢
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 1970-01-01
  • 2013-10-03
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多