Let's say I have following example GRanges:
> library(GenomicRanges)
> gr = GRanges(
+ seqnames = Rle(c("chr1", "chr2", "chr1", "chr3"), c(1, 3, 2, 4)),
+ ranges = IRanges(101:110, end = 111:120, names = head(letters, 10)),
+ strand = Rle(strand(c("-", "+", "*", "+", "-")), c(1, 2, 2, 3, 2)),
+ score = 1:10,
+ GC = seq(1, 0, length=10))
> gr
GRanges object with 10 ranges and 2 metadata columns:
seqnames ranges strand | score GC
<Rle> <IRanges> <Rle> | <integer> <numeric>
a chr1 [101, 111] - | 1 1
b chr2 [102, 112] + | 2 0.888888888888889
c chr2 [103, 113] + | 3 0.777777777777778
d chr2 [104, 114] * | 4 0.666666666666667
e chr1 [105, 115] * | 5 0.555555555555556
f chr1 [106, 116] + | 6 0.444444444444444
g chr3 [107, 117] + | 7 0.333333333333333
h chr3 [108, 118] + | 8 0.222222222222222
i chr3 [109, 119] - | 9 0.111111111111111
j chr3 [110, 120] - | 10 0
-------
seqinfo: 3 sequences from an unspecified genome; no seqlengths
It is straightforward to subset this GRanges as one would subset an R data.frame, e.g.
> gr$score
[1] 1 2 3 4 5 6 7 8 9 10
However, I am writing a function where the user would pass through a string for the metadata column to subset e.g.
subsetter = function(granges, column){
return(granges$column)
}
I try to use the function as follows:
> subsetter(gr, score)
which outputs NULL
This obvious doesn't work, as it will subset the gr
by column
, not score
.
> subsetter(gr, score)
NULL
If this was a data.frame, I could subset as follows:
gr[[(score)]]
but this gives the error
Error in gr[[(score)]] : this S4 class is not subsettable
Are there any other ways to subset a GRanges besides using $
?