我正在研究R中的一些数据,这些数据由三维空间和时间维度组成的四维数组组成:x,y,z,t。对于我的一些分析,我想获得一组空间坐标x,y,z的时间维度的所有数据。到目前为止,我已经使用了哪个函数来获得感兴趣空间位置的指数。但是,当我去获得与空间位置相对应的时间维度中的所有相关数据时,我无法找到一个优雅的R解决方案,并且使用了repmat,一个移植的MATLAB函数。如何动态索引多维R数组?
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])
该解决方案对于指定的目的可行,但在概念上看起来很丑。理想情况下,我想在最后一个2维矩阵:索引x时间。因此,在这种情况下,在查找中具有20个x,y,z坐标以及10个时间点,20 x 10矩阵将是理想的,其中行代表每行索引(不需要保留x,y,z ,值一定),每一列都是一个时间点。
在R中有这样做的好方法吗?我已经打得四处do.call(“[”,列表... 等,并使用外部和督促,但我所希望的,这些都没有奏效。
感谢您的任何建议! 迈克尔
谢谢,flodel!我知道我让这个问题比它需要的更复杂。是的,使用沿着最后一个维度的前三个索引正是我所需要的。谢谢你的帮助。 -Michael – 2012-07-17 13:31:36