4

I have array arr that can have any number of dimensions, say

arr <- array(NA, c(2,3,5))

I need a function getArrValues that takes as input a vector and uses this vector to extract values from the array:

getArrValues(arr, c(1,2,2)) # = arr[1,2,2]
getArrValues(arr, c(1,2))   # = arr[1,2,]
getArrValues(arr, c(1))     # = arr[1,,]

Do you have any ideas how this could be achieved? There is always a single index for a dimension, indexes are provided as a vector in the order of array dimensions, arrays can have any number of dimensions that is always greater or equal from the length of input vector.

Tim
  • 7,075
  • 6
  • 29
  • 58
  • 1
    See, also, [this](http://stackoverflow.com/questions/10865337/r-how-to-get-a-value-of-a-multi-dimensional-array-by-a-vector-of-indices), [this](http://stackoverflow.com/questions/17750893/how-to-pass-nothing-as-an-argument-to-for-subsetting) and [this](http://stackoverflow.com/questions/21443086/r-subsetting-n-dimensional-arrays) relevant posts. – alexis_laz Mar 22 '16 at 21:25
  • @Tim consider to accept an answer or provide a feedback why you think it is not answering your question – jangorecki Mar 30 '16 at 11:12

1 Answers1

1

It is quite straightforward to achieve using computing on the language.

arr <- array(NA, c(2,3,5))
getArrValues <- function(x, i) {
    stopifnot(is.array(x), is.numeric(i))
    if (!is.integer(i)) i = as.integer(i)
    li = as.list(i)[seq_along(dim(x))]
    li = lapply(li, function(x) if (!is.null(x)) x else substitute())
    eval(
        as.call(c(list(as.name("["), as.name("x")), li))
    )
}
getArrValues(arr, c(1,2,2)) # = arr[1,2,2]
getArrValues(arr, c(1,2))   # = arr[1,2,]
getArrValues(arr, c(1))     # = arr[1,,]

Just remove eval( call to investigate exact unevaluated call.

jangorecki
  • 16,384
  • 4
  • 79
  • 160