我正在尝试使用具有多个条件的专用函数来聚合栅格。我陷入了“if else”的语法中,并想知道是否有人可以提供帮助。
以下是我在agg.fun中尝试做的事情:
其他任何东西都是-9999
agg.fun <- function(x) {
if (max(x) == NA) {
return(-9999)
} else if (max(x) <= 100 && max(x) > 10) {
return(mean(x))
} else if (max(x) <= 10)) {
return(0)
} else if (max(x) > 100) {
cloud.count <- length(which(x==250))
cloud.per <- cloud.count/(ncol(x)*nrow(x))
if (cloud.per >= 0.3) {
return(-9999)
} else (cloud.per < 0.3) {
return(mean(x) + cloud.count * 0.5)
}
} else {
return(-9999)
}
}
r <- raster(matrix(rep(c(1:100),100),100,100))
#randomly set some values to 250
r[sampleRandom(r,1000,cells=TRUE)[,'cell']] <- 250
#randomly set some values to 200
r[sampleRandom(r,100,cells=TRUE)[,'cell']] <- 200
#set some values in raster to NA
r[r%in%c(200,201,211,225,237,239,254,255)] <- NA
#attempt to run aggregate (doesn't work right now)
r.agg <- aggregate(r, fact=3, fun=agg.fun, expand=TRUE, na.rm=TRUE)
答案 0 :(得分:2)
我认为你正在寻找这样的东西:
agg.fun <- function(x,...) { ## you should add ... for na.rm,and other extra parameters
x[is.na(x)] <- -9999
if (all(x <= 100 & x > 10))return(mean(x))
else{
len_100= sum(x>100)
len_missing = sum(x==-9999)
if(len_100 < 0.3*length(x))
return(mean(x)+ 0.5*len_missing)
}
return(-9999)
}