Entering edit mode
Can anyone share code for doing strand-aware GRanges shifts? I'd like to shift all the ranges in my GrangesList in by one from the regions 5' end.
Thanks!
Can anyone share code for doing strand-aware GRanges shifts? I'd like to shift all the ranges in my GrangesList in by one from the regions 5' end.
Thanks!
If you do not mind installing plyranges, its shift_upstream
function does it in a simple and readable way.
Example on GRanges
:
> GRanges(c("chr1:100-200:+", "chr1:100-200:-")) |> plyranges::shift_upstream(1)
GRanges object with 2 ranges and 0 metadata columns:
seqnames ranges strand
<Rle> <IRanges> <Rle>
[1] chr1 99-199 +
[2] chr1 101-201 -
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
You can endoapply
it to a GRangesList
object like that:
> list(GRanges("chr1:100-200:+"), GRanges("chr1:100-200:-")) |>
+ as("GRangesList") |>
+ endoapply(plyranges::shift_upstream, 1)
GRangesList object of length 2:
[[1]]
GRanges object with 1 range and 0 metadata columns:
seqnames ranges strand
<Rle> <IRanges> <Rle>
[1] chr1 99-199 +
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
[[2]]
GRanges object with 1 range and 0 metadata columns:
seqnames ranges strand
<Rle> <IRanges> <Rle>
[1] chr1 101-201 -
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
An option using GenomicRanges:
> gr<-GRanges(c("chr1:100-200:+", "chr1:100-200:-"))
> shiftStranded<-function(x, shift=0L,...) GenomicRanges::shift(x ,shift=shift*ifelse('-'==strand(x),-1,1),...)
> shiftStranded(gr ,1)
GRanges object with 2 ranges and 0 metadata columns:
seqnames ranges strand
<Rle> <IRanges> <Rle>
[1] chr1 101-201 +
[2] chr1 99-199 -
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
> shiftStranded(gr ,c(3,4))
GRanges object with 2 ranges and 0 metadata columns:
seqnames ranges strand
<Rle> <IRanges> <Rle>
[1] chr1 103-203 +
[2] chr1 96-196 -
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
edit: add example of how to use shiftStranded
on a GRangesList
(note use of mendoapply
allowing component-specific shifting):
> grl<-GRangesList(list(GRanges(c("chr1:100-200:+","chr1:200-300:-")), GRanges("chr1:100-200:-")))
> mendoapply(shiftStranded,grl ,c(3,4))
GRangesList object of length 2:
[[1]]
GRanges object with 2 ranges and 0 metadata columns:
seqnames ranges strand
<Rle> <IRanges> <Rle>
[1] chr1 103-203 +
[2] chr1 197-297 -
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
[[2]]
GRanges object with 1 range and 0 metadata columns:
seqnames ranges strand
<Rle> <IRanges> <Rle>
[1] chr1 96-196 -
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
Use of this site constitutes acceptance of our User Agreement and Privacy Policy.