简体   繁体   English

如何将function应用于R中的三维数组

[英]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.我想通过使用应用 function 来计算给定坐标在整个时间范围内的零数。我写了一个 function 来计算指定纬度和经度时的零数,但我似乎无法应用这个 function在整个阵列上。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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