R,在向量化的范围内加入

标签 r merge dplyr sqldf

我正在尝试连接两个数据集,其中一个数据集中的变量(或基因组中的位置)适合第二个数据集中的范围(基因开始/停止位置)。然而,位置不是唯一的,而是嵌套在一个额外的列(染色体)中。基因起始/终止位置也是如此。我的目标是将每个位置与相应的注释和效果链接起来。

例如:

library(sqldf)
set.seed(100)
a <- data.frame(
    annotation = sample(c("this", "that", "other"), 3, replace=TRUE),
    start = seq(1, 30, 10),
    chr = sample(1:3, 3, replace=TRUE)
  )
a$stop <- a$start + 10
b <- data.frame(
    chr = sample(1:3, 3, replace=TRUE),
    position = sample(1:15, 3, replace=TRUE),
    effect = sample(c("high", "low"), 3, replace=TRUE)
  )

SQL 内连接让我参与其中:

df<-sqldf("SELECT a.start, a.stop, a.annotation, b.effect, b.position
    FROM a, b
    inner JOIN a b on(b.position >= a.start and b.position <= a.stop);")

但这并不能解释每条染色体位置的重复。 我在将其包装到循环或应用函数中时遇到概念上的问题。

我对 SQL 并不执着,这只是我以前解决一个更简单问题的方式。我也不确定制作额外的索引列是否合适,因为我有数千个染色体值。

我想要的输出如下所示:

    df$chr<-c("NA","2","2")
      start stop annotation effect position chr
1     1   11       this   high        3  NA
2     1   11       this   high       10  NA
3    11   21       this    low       14   2

每个 position 都位于正确 chr 上的 startstop 点之间,或者给定NA,其中 chr 上没有任何点匹配。

最佳答案

development version data.table 引入了非相等连接,允许:

library(data.table)
setDT(a) # converting to data.table in place
setDT(b)

b[a, on = .(position >= start, position <= stop), nomatch = 0,
  .(start, stop, annotation, effect, x.position, chr = ifelse(i.chr == x.chr, i.chr, NA))]
#   start stop annotation effect x.position chr
#1:     1   11       this   high          3  NA
#2:     1   11       this   high         10  NA
#3:    11   21       this    low         14   2

关于R,在向量化的范围内加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37147441/

相关文章:

R - 在 jupyter 中更改 ggplot 绘图大小

php - 合并 SQL 记录

algorithm - 合并不同项目的排名列表

r - 如何以编程方式在数据框中分配一堆变量

regex - 提取R中符号周围的字符

r - 为什么在 R 中使用 `format()` 和 `dplyr` 会出现奇怪的行为?

R mutate 不会添加列

r - 要列出的分组数据框

r - 使用 lubridate 计算日期间隔内的日历天数

ios - xCode 4.5 git merge 无法提交或报错