我有一个水温[lon,lat,depth,month]的4维数组,我想根据矩阵提取每月温度,其中行和列分别为lon和lat,值为深度级别。结果将是在可变深度[月,纬度,月]的月度温度的三维阵列。
仅提供一个例子:
0
我查看了How to index a multidimensional R array dynamically?和R use matrix to select row of multidimensional array,但无法解决该怎么做?
非常感谢任何帮助。
答案 0 :(得分:3)
可以离开,但这是一次尝试:
#get the indices relative to lon, lat and depth
threeIndices<-cbind(c(row(depth)),c(col(depth)),c(depth))
#repeat each row of the above to host a different month value
threeIndices<-threeIndices[rep(1:nrow(threeIndices),dim(temperature)[4]),]
#define the month index
fourthIndex<-rep(1:dim(temperature)[4],each=nrow(threeIndices)/dim(temperature)[4])
#putting all together
allIndices<-cbind(threeIndices,fourthIndex)
#subsetting and putting in an array
array(temperature[allIndices],dim(temperature)[c(1,2,4)])
答案 1 :(得分:1)
Nicola的回答帮了很多忙。我想出了一种可能更快的方法,没有根据建议单独指定每个月。
#get the indices relative to lon, lat and depth
threeIndices <- cbind(c(row(depth)),c(col(depth)),c(depth))
# subset and put back in array
temperature.depth <- array(apply(temperature, 4, `[`, threeIndices), dim = dim(temperature)[c(1,2,4)])