Extract a subset of an array, matrix or a vector with unknown dimensions.

This method is useful when you do not know the number of dimensions of the object your wish to extract values from, cf. example.

# S3 method for array
extract(x, ..., indices=list(...), dims=names(indices), drop=FALSE)

Arguments

x

An array or a matrix.

...

These arguments are by default put into the indices list.

indices

A list of index vectors to be extracted.

dims

An vector of dimensions - one per element in indices - which will be coerced to integers. If NULL, it will default to seq_along(indices).

drop

If TRUE, dimensions of length one are dropped, otherwise not.

Value

Returns an array.

Author

Henrik Bengtsson

See also

Examples

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Example using an array with a random number of dimensions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
maxdim <- 4
dim <- sample(3:maxdim, size=sample(2:maxdim, size=1), replace=TRUE)
ndim <- length(dim)
dimnames <- list()
for (kk in 1:ndim)
  dimnames[[kk]] <- sprintf("%s%d", letters[kk], 1:dim[kk])
x <- 1:prod(dim)
x <- array(x, dim=dim, dimnames=dimnames)

cat("\nArray 'x':\n")
#> 
#> Array 'x':
print(x)
#>    b1 b2 b3 b4
#> a1  1  4  7 10
#> a2  2  5  8 11
#> a3  3  6  9 12


cat("\nExtract 'x[2:3,...]':\n")
#> 
#> Extract 'x[2:3,...]':
print(extract(x, "1"=2:3))
#>    b1 b2 b3 b4
#> a2  2  5  8 11
#> a3  3  6  9 12

cat("\nExtract 'x[3,2:3,...]':\n")
#> 
#> Extract 'x[3,2:3,...]':
print(extract(x, "1"=3,"2"=2:3))
#>    b2 b3
#> a3  6  9

cat("\nExtract 'x[...,2:3]':\n")
#> 
#> Extract 'x[...,2:3]':
print(extract(x, indices=2:3, dims=length(dim(x))))
#>    b2
#> a1  4
#> a2  5
#> a3  6



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Assertions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
y <- array(1:24, dim=c(2,3,4))
yA <- y[,,2:3]
yB <- extract(y, indices=list(2:3), dims=length(dim(y)))
stopifnot(identical(yB, yA))

yA <- y[,2:3,2]
yB <- extract(y, indices=list(2:3,2), dims=c(2,3), drop=TRUE)
stopifnot(identical(yB, yA))