Ilik
Ilik

Reputation: 165

R count occurrences on a multidimensional array

I have a 4-dimensional array in R (lat, lon, time, variables) and I need to count for each variable the number of cases where the value is greater than x for each grid point (i.e., a lat-lon combination). So the result should be a series of N maps (N = number of variables) (i.e., 2D array of lat-lon) with the values as integer counting the number of times the variable is greater than x. The array dimensions are [60,185,8760,5]. I tried playing with tapply() but couldn't figure it out.

a reproducible example:

MyArray = array(rnorm(72), dim=c(3,4,2,3))
x = 0.7
which(MyArray[,,,1]>x)

Any ideas? Thanks, Ilik

Upvotes: 1

Views: 590

Answers (1)

bgoldst
bgoldst

Reputation: 35324

apply(MyArray,c(1,2,4),function(slice) sum(slice>x));
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]    0    0    0    0
## [2,]    1    1    0    0
## [3,]    1    0    0    1
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]    0    1    0    0
## [2,]    0    1    1    0
## [3,]    1    0    0    0
## 
## , , 3
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    0    1    0
## [2,]    0    0    0    0
## [3,]    1    1    1    0

Upvotes: 2

Related Questions