```
## ---------------------------------------------------------------------
## A. SET OPERATIONS
## ---------------------------------------------------------------------
x <- GRanges("chr1", IRanges(c(2, 9) , c(7, 19)), strand=c("+", "-"))
y <- GRanges("chr1", IRanges(5, 10), strand="-")
union(x, y)
union(x, y, ignore.strand=TRUE)
intersect(x, y)
intersect(x, y, ignore.strand=TRUE)
setdiff(x, y)
setdiff(x, y, ignore.strand=TRUE)
## With 2 GRangesList objects:
gr1 <- GRanges(seqnames="chr2",
ranges=IRanges(3, 6))
gr2 <- GRanges(seqnames=c("chr1", "chr1"),
ranges=IRanges(c(7,13), width = 3),
strand=c("+", "-"))
gr3 <- GRanges(seqnames=c("chr1", "chr2"),
ranges=IRanges(c(1, 4), c(3, 9)),
strand=c("-", "-"))
grlist <- GRangesList(gr1=gr1, gr2=gr2, gr3=gr3)
union(grlist, shift(grlist, 3))
intersect(grlist, shift(grlist, 3))
setdiff(grlist, shift(grlist, 3))
## Sanity checks:
grlist2 <- shift(grlist, 3)
stopifnot(identical(
union(grlist, grlist2),
mendoapply(union, grlist, grlist2)
))
stopifnot(identical(
intersect(grlist, grlist2),
mendoapply(intersect, grlist, grlist2)
))
stopifnot(identical(
setdiff(grlist, grlist2),
mendoapply(setdiff, grlist, grlist2)
))
## ---------------------------------------------------------------------
## B. PARALLEL SET OPERATIONS
## ---------------------------------------------------------------------
punion(x, shift(x, 6))
## Not run:
# punion(x, shift(x, 7)) # will fail
# ## End(Not run)
punion(x, shift(x, 7), fill.gap=TRUE)
pintersect(x, shift(x, 6))
pintersect(x, shift(x, 7))
psetdiff(x, shift(x, 7))
## ---------------------------------------------------------------------
## C. MORE EXAMPLES
## ---------------------------------------------------------------------
## GRanges object:
gr <- GRanges(seqnames=c("chr2", "chr1", "chr1"),
ranges=IRanges(1:3, width = 12),
strand=Rle(strand(c("-", "*", "-"))))
## Parallel intersection of a GRanges and a GRangesList object
pintersect(gr, grlist)
pintersect(grlist, gr)
## For a fast 'mendoapply(intersect, grlist, as(gr, "GRangesList"))'
## call pintersect() with 'strict.strand=TRUE' and call reduce() on
## the result with 'drop.empty.ranges=TRUE':
reduce(pintersect(grlist, gr, strict.strand=TRUE),
drop.empty.ranges=TRUE)
## Parallel set difference of a GRanges and a GRangesList object
psetdiff(gr, grlist)
```

Run the code above in your browser using DataCamp Workspace