Lukas
Lukas

Reputation: 727

Subsetting multidimensional array using matrix in R

I have a 4 dimensional array of water temperatures [lon, lat, depth, month] and I want to extract monthly temperatures based on a matrix where the rows and columns are lon and lat respectively and the values the depth levels. The result would be a 3 dimensional array of monthly temperatures at variable depth [lon, lat, month].

Just to provide an example:

set.seed(1)    
temperature <- array(rnorm(10), rep(3,4))
depth <- matrix(c(NA, sample(1:3, 8, replace = TRUE)), 3, 3)

I had a look at How to index a multidimensional R array dynamically? and R use matrix to select row of multidimensional array but can't work out how to do this?

Any help is much appreciated.

Upvotes: 0

Views: 1031

Answers (2)

Lukas
Lukas

Reputation: 727

Nicola's answer helped a lot. I figured out a potentially quicker way without specifying each month individually based on the suggestion.

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

Upvotes: 1

nicola
nicola

Reputation: 24480

Can be way off, but that's a try:

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

Upvotes: 4

Related Questions