File: subset.R

package info (click to toggle)
r-bioc-spatialexperiment 1.16.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,648 kB
  • sloc: makefile: 2
file content (57 lines) | stat: -rw-r--r-- 1,453 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#' @name SpatialExperiment-subset
#' 
#' @title Subsetting SpatialExperiment objects
#' 
#' @aliases [,SpatialExperiment,ANY,ANY,ANY-method
#' 
#' @description
#' The subsetting method for \code{\link{SpatialExperiment}} objects ensures
#' that spatial data attributes (\code{\link{spatialCoords}} and
#' \code{\link{imgData}}) are subsetted correctly to match rows and columns with
#' the remainder of the object.
#' 
#' @section subset:
#' \describe{
#' \item{\code{[}:}{ subsetting method}
#' }
#' 
#' @param x a \code{\link{SpatialExperiment}} object
#' @param i row indices for subsetting
#' @param j column indices for subsetting
#' 
#' @return a \code{\link{SpatialExperiment}} object
#' 
#' @examples
#' example(read10xVisium)
#' 
#' dim(spe)
#' 
#' set.seed(123)
#' idx <- sample(ncol(spe), 10)
#' sub <- spe[, idx]
#' dim(sub)
#' colData(sub)
#' spatialCoords(sub)
NULL

# we overwrite the default subsetting method
# to assure that the 'imgData' and 'spatialData' are subsetted if columns/rows 
# are dropped

#' @importFrom methods callNextMethod
#' @export
setMethod("[",
    c("SpatialExperiment", "ANY", "ANY"),
    function(x, i, j, ..., drop=FALSE) {
        if (missing(i)) i <- TRUE
        if (missing(j)) j <- TRUE
        x <- callNextMethod()
        if ( !isEmpty(imgData(x)) ) {
            keep <- imgData(x)$sample_id %in% unique(x$sample_id)
            imgData(x) <- imgData(x)[keep, ]
        }
        return(x)
    }
)