Value intervals windows in R

Viewed 38

I have several windows interval looking like that:

Start       Stop
19136293    19138512
20708651    20716555
31063462    31064384

And then I have data looking like that:

Read TrueC MapC TruePos     MappedPos   ResMap
JLN6    22  22  16050005    16050091    TP
9MRW    22  22  16050032    16050032    TP
GRR3    22  14  16050075    19792677    FP
V19X    22  *   17023341    0           FN 

And I am trying to find the amount of read inside and outside the previous windows; a read is inside the window if TruePos value is inside one window interval. My goal is to have the amount of TP/FP/FN (ResMap column) inside and outside the windows.

I wanted to create for loop on my windows file and then check each line of my datas one by one and sum it but I have 600 Millions lines and I am sure there is a quickest way.. I just don't know it.

Thanks a lot,

Cheers,

Cagami

1 Answers

Since, you have not provided any reproducible data, I have used some sample data of my own

dput(range)
structure(list(start = c(10L, 25L, 50L, 61L, 85L, 100L), end = c(15L, 
27L, 53L, 66L, 89L, 102L)), class = "data.frame", row.names = c(NA, 
-6L))

> range
  start end
1    10  15
2    25  27
3    50  53
4    61  66
5    85  89
6   100 102

> dput(df)
structure(list(Id = 1:15, truepos = c(65L, 59L, 61L, 74L, 92L, 
49L, 72L, 96L, 81L, 2L, 34L, 27L, 66L, 87L, 19L)), class = "data.frame", row.names = c(NA, 
-15L))

> df
   Id truepos
1   1      65
2   2      59
3   3      61
4   4      74
5   5      92
6   6      49
7   7      72
8   8      96
9   9      81
10 10       2
11 11      34
12 12      27
13 13      66
14 14      87
15 15      19

I have used package named fuzzyjoin to do like this, which will add a new column inside_range giving value as True whenever the TRUEPOS is inside one of the ranges

library(fuzzyjoin)
fuzzy_left_join(df, range, by = c("truepos" = "start", "truepos" = "end"), 
                match_fun = list(`>=`, `<`)) %>% mutate(inside_range = !is.na(start)) %>%
  select(-start, -end)

>  Id truepos inside_range
1   1      65         TRUE
2   2      59        FALSE
3   3      61         TRUE
4   4      74        FALSE
5   5      92        FALSE
6   6      49        FALSE
7   7      72        FALSE
8   8      96        FALSE
9   9      81        FALSE
10 10       2        FALSE
11 11      34        FALSE
12 12      27        FALSE
13 13      66        FALSE
14 14      87         TRUE
15 15      19        FALSE

I think this serves your purpose and you can replicate this methodology on your data df. Good Luck

Related