如何动态索引多维R数组?

Mic*_*ist 3 r multidimensional-array

我正在研究R中的一些数据,这些数据包括由三个空间维度和时间维度组成的四维数组:x,y,z,t.对于我的一些分析,我想获得一组空间坐标x,y,z的时间维度中的所有数据.到目前为止,我已经使用哪个函数来获得感兴趣的空间位置的索引.但是当我去获取与空间位置相对应的时间维度中的所有相关数据时,我找不到优雅的R解决方案并且已经使用了repmat,一个移植的MATLAB函数.

a4d <- array(rnorm(10000), rep(10,4)) #x, y, z, t

#arbitrary set of 3d spatial indices x, y, z (here, using high values at first timepoint)
indices <- which(a4d[,,,1] > 2, arr.ind=TRUE)
str(indices)

# int [1:20, 1:3] 10 2 6 5 8 2 6 8 2 10 ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:3] "dim1" "dim2" "dim3"

#Now, I would like to use these indices to get data x, y, z for all t

#Intuitive, but invalid, syntax (also not clear what the structure of the data would be)
#a4d[indices,]

#Ugly, but working, syntax
library(pracma)

#number of timepoints
nt <- dim(a4d)[4]

#create a 4d lookup matrix
lookup <- cbind(repmat(indices, nt, 1), rep(1:nt, each=nrow(indices)))

#obtain values at each timepoint for indices x, y, z
result <- cbind(lookup, a4d[lookup])
Run Code Online (Sandbox Code Playgroud)

这个解决方案适用于所述目的,但在概念上似乎很难看.理想情况下,我想在最后得到一个二维矩阵:索引x时间.因此,在这种情况下,在查找中使用20 x,y,z坐标,以及10个时间点,20 x 10矩阵将是理想的,其中行表示每行索引(不需要保留x,y,z ,值必然),每列是一个时间点.

在R中有一个很好的方法吗?我玩过do.call("[",列表......等等,并使用外部和prod,但这些没有按照我的希望工作).

谢谢你的任何建议!迈克尔

flo*_*del 7

我想你正在寻找:

apply(a4d, 4, `[`, indices)
Run Code Online (Sandbox Code Playgroud)

并检查我们的结果是否匹配:

result1 <- matrix(result[,5], ncol = 10)
result2 <- apply(a4d, 4, `[`, indices)
identical(result1, result2)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)