如何根据值范围匹配数据

How to match data based on a range of values

我有 2 个遗传数据集,我试图在其中查找基因组 (file1) 中某个位置的变体是否 matching/found 在我在另一个数据集 (file2) 中的任何行的范围内,然后提取文件 2 中找到的匹配项与文件 1 合并。一个条件是匹配项仅在具有相同染色体的情况下搜索变体。例如:

文件 1:

Chromosome    Position
1              3
1              47
2              10
3              2

文件 2:

Chromosome    Start    End
1              101      102
1              40       50  
2              40       50
3              20       22

预期输出:

Chromosome    Start    End
1              40       50 
#this is the only row from which a variant from file1 fits in its position range and is on the same chromosome

理想情况下,我会合并 file1 变体以与其在同一行的 file2 中匹配的染色体开始和结束位置对齐,但我是 R 的新手并且停留在尝试匹配变体的第一步基于它的位置号是否在第二个文件的范围内。目前我正在尝试适应:

dt1[ dt2, match := i.,ID  #including a made-up ID column for the sake of trying to adapt this code 
     on = .(Chromosome, Position > Start, Position < End ) ]

但这似乎不起作用,除此之外我不知道如何开始。任何有关如何解决此问题的帮助将不胜感激

数据:

dput(file1)
structure(list(Chromosome = c(1L, 1L, 2L, 3L), Position = c(3L, 
47L, 10L, 2L)), row.names = c(NA, -4L), class = c("data.table", 
"data.frame"))

dput(file2)
structure(list(Chromosome = c(1L, 1L, 2L, 3L), Start = c(101L, 
40L, 40L, 20L), End = c(102L, 50L, 50L, 22L)), row.names = c(NA, 
-4L), class = c("data.table", "data.frame"))

您可以使用 tidyverse 包进行一些重新编码并获得 chromosomes,其中 Position 值介于 StartEnd 之间。

library(tidyverse)

df<-file1 %>%
  # Join by Chromosome, it will duplicate each Position by Start and End Values
  left_join(file2, 
            by = "Chromosome") %>% 
  # Create a new column to indicate if the Position is between Start and End values
  mutate(isRange = Position >= Start & Position <= End) %>%
  # Filter to stay with only the chromosomes where the previous condition is met
  filter(isRange)