R/acorn.R

Defines functions acorn.default acorn

Documented in acorn acorn.default

acorn <- function(x, n=6, m=5, r=1, ...) UseMethod('acorn')

acorn.default <- function(x, n=6, m=5, r=1, ..., addrownums = TRUE) {
    stopifnot(length(n) == 1L)
    stopifnot(length(m) == 1L)
    stopifnot(length(r) == 1L)
    if (is.null(dim(x)))
        if (n >= 0) return(head(x, n)) else return(tail(x, -n))
    n <- sign(n)*min(abs(n), nrow(x))
    ns <- if (n >= 0) seq(length.out=n) else seq(length.out=-n, to=nrow(x))
    as <- list(ns)
    if (length(dim(x))>1) {
        m <- sign(m)*min(abs(m), ncol(x))
        ms <- if (m >= 0) seq(length.out=m) else seq(length.out=-m, to=ncol(x))
        as <- c(as, list(ms))
    }
    if (length(dim(x))>2) {
        r <- sign(r)*min(abs(r), dim(x)[3])
        rs <- if (r >= 0) seq(length.out=r) else seq(length.out=-r, to=dim(x)[3])
        as <- c(as, list(rs))
    }
    if (length(dim(x))>3) {
        args <- list(...)
        for (i in seq(4, length(dim(x)))) {
            if (length(args) >= i-3)
                a <- args[[i-3]]
            else
                a <- 1
            a <- sign(a)*min(abs(a), dim(x)[i])
            as <- c(as, list(if (a >= 0) seq(length.out=a) else seq(length.out=-a, to=dim(x)[i])))
        }
    }
    y <- asub(x, as, drop=FALSE)
    if (addrownums) {
        if (is.null(dimnames(y)))
            dimnames(y) <- vector('list', length(dim(x)))
        for (i in seq(length.out=length(dim(x))))
            if (is.null(dimnames(y)[[i]]))
                dimnames(y)[[i]] <- paste0('[', as[[i]], ']')
    }
    y
}

Try the abind package in your browser

Any scripts or data that you put into this service are public.

abind documentation built on Sept. 13, 2024, 1:06 a.m.