Here is some code to construct an exemplary array:
my.array <- array(sample(1:100, replace=T), c(54,71,360))
The array contains climatological data. While the first two dimensions 54 and 71
represent coordinates, the third dimension 360
represents the amount of time steps.
Now I want to extract every nth time step, let's say every third time step, so that the resulting array is of the dimensions c(54,71,120)
.
This is what I tried:
new.array <- apply(my.array, 1:2, function(x) x[seq(0, 360, 3)])
But it leads to an output of wrong dimensions c(120,54,71)
.
Anybody with an idea?
CodePudding user response:
Try
my.array[,,seq(1,360,3)]
which has
> dim(my.array[,,seq(1,360,3)])
[1] 54 71 120
CodePudding user response:
A way is to subset with a boolean vector. To get every third element c(TRUE, FALSE, FALSE)
could be used, which will start with the first, than the fourth, ... The advantage is, that you don't need to ask for the size of the dimension you want to subset. And if you want to start from the second simply use c(FALSE, TRUE, FALSE)
.
my.array[,,c(TRUE, FALSE, FALSE)]