[英]How to Calculate the percent difference in a three dimensional array using R apply()
[英]How to apply a function to a three dimensional array in R
我有一个包含时间(以年为单位)、纬度和经度的三维数组。 我想通过使用应用 function 来计算给定坐标在整个时间范围内的零数。我写了一个 function 来计算指定纬度和经度时的零数,但我似乎无法应用这个 function在整个阵列上。 我的代码:
#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
尝试:
# 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.