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