2

I have an array x that I don't know its dimension in advance. How do I index only the last dimension? For example:

trimGibbsChain <- function (x, ntrim) {
    toTrim <- -(1:ntrim)
    return(x[,,,toTrim]) # How many commas?
}

The problem is, when you don't know the dimension of the array, you don't know how many commas to put there. What is the fastest way to do this?

  • 3
    You might find something [here](http://stackoverflow.com/questions/10865337/r-how-to-get-a-value-of-a-multi-dimensional-array-by-a-vector-of-indices) and [here](http://stackoverflow.com/questions/17750893/how-to-pass-nothing-as-an-argument-to-for-subsetting) – alexis_laz May 21 '17 at 17:45

1 Answers1

1

Solution based on links in alexis_laz's comment

This can be done by subsetting with [ using list as indices:

lastInd <- function(x, n){
    nd <- length(dim(x))
    # uncomment the following line if x could be a plain vector without dim
    # if(nd == 0) nd = 1
    inds <- rep(alist(,)[1], nd)
    inds[nd] <- n
    do.call(`[`, c(list(x), inds))
}

Original answer

Couldn't find one existing function, but the following should work: x is an array with at least 2-dim; n is the index along the last dim;

lastInd <- function(x, n){
    d <- dim(x)
    d.new <- d[-length(d)]
    block.size <- prod(d.new)
    res <- x[(block.size * (n - 1) + 1):(block.size * n)]
    array(res, dim = d.new)
}

To handle the case when x is a plain vector:

lastInd <- function(x, n){
    d <- dim(x)
    if(is.null(d)){
        x[n]
    }else{
        d.new <- d[-length(d)]
        block.size <- prod(d.new)
        res <- x[(block.size * (n - 1) + 1):(block.size * n)]
        array(res, dim = d.new)
    }
}

An example:

x <- array(1:12, dim = c(2, 2, 3))
lastInd(x, 2)

#      [,1] [,2]
# [1,]    5    7
# [2,]    6    8

lastInd(2:4, 3)
# [1] 4
mt1022
  • 16,834
  • 5
  • 48
  • 71