Search code examples
rautocompletebioconductorr-s4

Why "$" autocompletion works for S4 class "SummarizedExperiment" from BioConductor


I am having hard time understanding how autocompletion can work for a custom made S4 class in BioConductor called "SummarizedExperiment".

Here is a short demonstration taken from example(SummarizedExperiment):

library(SummarizedExperiment)

nrows <- 200; ncols <- 6
counts <- matrix(runif(nrows * ncols, 1, 1e4), nrows)

rowRanges <- GRanges(rep(c("chr1", "chr2"), c(50, 150)),
                     IRanges(floor(runif(200, 1e5, 1e6)), width=100),
                     strand=sample(c("+", "-"), 200, TRUE),
                     feature_id=sprintf("ID%03d", 1:200))

colData <- DataFrame(Treatment=rep(c("ChIP", "Input"), 3), row.names=LETTERS[1:6])

rse <- SummarizedExperiment(assays=SimpleList(counts=counts),
                            rowRanges=rowRanges, colData=colData)

Now this object is:

> structure(rse)
class: RangedSummarizedExperiment
dim: 200 6
metadata(0):
assays(1): counts
rownames: NULL
rowData names(1): feature_id
colnames(6): A B ... E F
colData names(1): Treatment

Seems to have it's own generic $ function LINK:

setMethod("$", "SummarizedExperiment",
    function(x, name)
{
    colData(x)[[name]]
})

Yet when I press tab in R console it autocompletes the possible names for $:

rse$<tab>
rse$Treatment

Why is this happening? I thought R only autocompleted $ for lists.


Solution

  • The implementation of tab completion is via the S3 generic ?.DollarNames. For SummarizedExperiment, the relevant method is

    .DollarNames.SummarizedExperiment <- function(x, pattern = "")
        grep(pattern, names(colData(x)), value=TRUE)
    

    Approximately, when the tab key is pressed, R looks for a pattern x$foo<tab>, finds that x is a SummarizedExperiment, and so looks for .DollarNames.SummarizedExperiment to evaluate, passing x as the first argument and foo as the second, offering completions returned by the method.

    In contrast, when the carriage return is pressed x$foo<cr>, R sees that you are trying to invoke $ on x, and so looks for the (S4) method for $.