-
-
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) |
Thanks!
@BenBondLamberty pointed me towards the abind
package, wherein the asub
function does the trick, in the same style as your answer. So the simplest solution seems to be:
library(abind)
asub(x, i, 1)
For an array x
and index i
on the first dimension
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Eew. Nasty problem. From the look of ?"[" there is no "right" way to do this, which is weird. But I guess arrays come in small enough numbers of dimensions you could probably just work with if/else blocks.
Here's marginally less hacky version that avoids
eval(parse())
(seefortunes::fortune("parse")
):(this generalises your solution so passing a number other than 1 in to the
dim
argument subsets thedim
'th dimension, sogeti(x, 1, 2)
gets the first slice through the second dimension).