如何动态索引多维R数组? [英] How to index a multidimensional R array dynamically?

查看:26
本文介绍了如何动态索引多维R数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on some data in R that consist of four-dimensional arrays composed of three spatial dimensions and a time dimension: x, y, z, t. For some of my analyses, I would like to obtain all of the data in the time dimension for a set of spatial coordinates x, y, z. Thus far, I have used the which function to obtain the indices of the spatial locations of interest. But when I go to obtain all relevant data in the time dimension corresponding to the spatial locations, I cannot find an elegant R solution and have resorted to using repmat, a ported MATLAB function.

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])

此解决方案可以满足所述目的,但在概念上看起来很丑陋.理想情况下,我希望最后有一个二维矩阵:索引 x 时间.因此,在这种情况下,在查找中有 20 个 x、y、z 坐标和 10 个时间点的情况下,20 x 10 矩阵将是理想的,其中行代表每行索引(不需要保留 x、y、z,必须是值),每一列都是一个时间点.

This solution works okay for the stated purpose, but seems ugly conceptually. Ideally, I would like a 2-dimensional matrix at the end: index x time. So, in this case, with 20 x, y, z coordinates in the lookup, and 10 timepoints, a 20 x 10 matrix would be ideal where rows represent each row of indices (don't need to preserve the x, y, z, values necessarily) and each column is a timepoint.

在 R 中有没有好的方法可以做到这一点?我玩过 do.call("[", list ...等等,并使用了外部和产品,但这些并没有像我希望的那样工作.

Is there is a good way to do this in R? I have played around with do.call("[", list ... etc. and using outer and prod, but these haven't worked as I had hoped.

感谢您的任何建议!迈克尔

Thanks for any suggestions! Michael

推荐答案

我认为您正在寻找:

apply(a4d, 4, `[`, indices)

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

And to check that our results match:

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

这篇关于如何动态索引多维R数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆