简体   繁体   中英

How to apply a function to a three dimensional array in R

I have a three dimensional array containing time (in years), latitude, and longitude. I would like to count the number of zeros a given coordinate has over the entire timescale by using the apply function. I have written a function to count the number of zeros when I specify a latitude and longitude, but I cannot seem to apply this function over the entire array. My code:

#to sum zeros at a given lat and lon across all years combined
sum.zero <- function(x, lat, lon) {
  sum(is.zero(x[,lat,lon]))
  
}

#to test for zero 
is.zero <- function(x) {
  x == 0 


}
 numberofzeros <- apply(data, c(2,3), sum.zero)

 Error in x[, lat, lon] : incorrect number of dimensions 

Try:

# test data
data <- array(c(1, 0, 0, 0, 1, 1, 1, 0), dim = c(2,2,2))
apply(data, c(2,3), function (x) sum(x==0))
     [,1] [,2]
[1,]    1    0
[2,]    2    1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM