2

I have a data.frame which consists of linear intervals for each id:

df <- data.frame(id = c(rep("a",3),rep("b",4),rep("d",4)),
                 start = c(3,4,10,5,6,9,12,8,12,15,27),
                 end = c(7,8,12,8,9,13,13,10,15,26,30))

I'm looking for an efficient function that will unite all intersecting intervals per each id. For df the result ill be:

res.df <- data.frame(id = c("a","a","b","d","d","d"),
                     start = c(3,10,5,8,12,27),
                     end = c(8,12,13,10,26,30))

For which eventually I'll be able to sum up all the united intervals per each id to get their combined length:

sapply(unique(res.df$id), function(x) sum(res.df$end[which(res.df$id == x)]-res.df$start[which(res.df$id == x)]+1))
user1701545
  • 5,706
  • 14
  • 49
  • 80
  • This might be useful: http://stackoverflow.com/questions/27574775/is-it-possible-to-use-the-r-data-table-funcion-foverlaps-to-find-the-intersectio – thelatemail Mar 21 '16 at 01:34

1 Answers1

3
#source("https://bioconductor.org/biocLite.R")
#biocLite("IRanges")
library(IRanges)
df1 <- as(df, "RangedData")

as.data.frame(reduce(df1, by = "id", min.gapwidth = 0.5))

#  space start end width id
#1     1     3   8     6  a
#2     1    10  12     3  a
#3     1     5  13     9  b
#4     1     8  10     3  d
#5     1    12  26    15  d
#6     1    27  30     4  d
Roland
  • 127,288
  • 10
  • 191
  • 288