So, I'm working on extracting values from multiple different rasters in R. However, some of our data is marine, some terrestrial. Some rasters cover both, but a few are ocean only or land only. At times, this leads to extract in the raster package throwing errors in unpredictable ways.
For example, if I throw a land point into the mix when extracting sea surface temperatures, I WANT an NA return value. However, despite my best efforts, I still get the dreaded
Error in apply(x, 2, fun2) : dim(X) must have a positive length
error.
I don't get it consistently. Sometimes I get NA returns, which is what I want. But for some points...no. Here's what I've done. Does anyone have any pointers on avoiding how this extraction breaks?
To try this example, grab the data from http://www.metoffice.gov.uk/hadobs/hadisst/data/HadISST_sst.nc.gz
library(raster)
hadsst <- raster::brick("./HadISST_sst.nc")
#A lat/long throwing errors
ull <- data.frame(site_lat = 37.6, site_long = 101.3)
#A function to make things safe
safe_mean <- function(x){
if(sum(is.na(x))==length(x)) return(NA)
if(sum(x == -1000, na.rm=T) == length(x)) return(NA)
return(max(x, na.rm=T))
}
#Where it all goes wrong
hadsst_vals <- raster::extract(hadsst,
cbind(ull$site_long, ull$site_lat),
buffer=50000, fun=safe_mean, na.rm=FALSE)