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


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


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)

To work this out, I would do

hadsst_list <- raster::extract(hadsst, cbind(ull$site_long, ull$site_lat), buffer=50000)

and then

sapply(hadsst_list, safe_mean)

if that fails

for (i in 1:length(hadsst_list)) {


to see why this happens.

  • This is brilliant. And even faster with purrr - although map_df in purrr behaves strangely with single row outputs. – jebyrnes Feb 25 '16 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.