-
-
Save goldingn/407bb7b9eb602eb60b81 to your computer and use it in GitHub Desktop.
return the elements of an array of unknown dimension at the ith index on the first dimension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
geti <- function (x, i) { | |
# return the elements of an array `x` of unknown dimension | |
# at the ith index of its first dimension | |
# throw an error if x isn't an array | |
stopifnot(is.array(x)) | |
# get the dimension of x | |
k <- length(dim(x)) | |
# build an expression as text | |
expr <- paste('x[i,', | |
paste(rep(',', k - 2), collapse = ' '), | |
']') | |
# evaluate it | |
ans <- eval(parse(text = expr)) | |
# return this | |
return (ans) | |
} | |
# # test it | |
# # make an array | |
# arr <- array(rnorm(3 * 4 * 2), | |
# dim = c(3, 4, 2)) | |
# # print it | |
# arr | |
# | |
# # get the elements at 2 on the first dimension | |
# geti(arr, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!
@BenBondLamberty pointed me towards the
abind
package, wherein theasub
function does the trick, in the same style as your answer. So the simplest solution seems to be:For an array
x
and indexi
on the first dimension