climsaver
climsaver

Reputation: 617

How to calculate the sum of a dimension of an array and redistribute it to the other dimensions?

I am working with climatalogical data that consists of a gridded data set of hourly precipitation values. The grid consists of 300 x 300 points (which include the geographical coordinates) and the data values are for one day period (24 hours), so the resulting array has the dimensions 300 300 24.

Now I need to calculate the day sum of the precipitation for the same grid. So what needs to be done is to sum up all the values in the third dimension of the array and assign these day sum values to the same grid values from the first two dimensions. The resulting dimensions should then be 300 300 1.

Anybody with an advice how to achieve that?

Upvotes: 0

Views: 76

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

You can use apply across the first two dimensions.

Suppose I have an array with the same dimensions as the one in your question:

set.seed(69)

data_array <- array(runif(300 * 300 * 24), dim = c(300, 300, 24))

dim(data_array)
#> [1] 300 300  24

Now if I wanted the daily sum of the precipitation in the cell on the very top left of the grid, I could do:

sum(data_array[1, 1, ])
#> [1] 12.04836

So to get it for every cell in the grid, I use apply over the first two dimensions:

result <- apply(data_array, 1:2, sum)

This gives me a 300 * 300 grid:

dim(result)
#> [1] 300 300

And we can see that the top left cell has the sum of the top left cells of each of the 24 slices of the array:

result[1, 1]
#> [1] 12.04836

Upvotes: 1

Related Questions