Search code examples
rrasterr-raster

"IDs do not match" error when extracting raster values at SpatialLines


I want to extract a raster's values where a spatialLines object crosses its cells, and am hitting an error. This illustrates:

> require(maptools); require(raster)
> data(wrld_simpl)
> nepal = as(wrld_simpl[wrld_simpl$NAME == 'Nepal',], 'SpatialLines')
> r = raster(volcano)
> extent(r) = c(79,90,26,31)
> plot(r); plot(nepal, col='red', add=T)

enter image description here

The extraction:

> border_values = extract(r, nepal, sp=T, fun=median)
Error in SpatialLinesDataFrame(y, res[, -1, drop = FALSE]) : 
  row.names of data and Lines IDs do not match

Any idea what's causing this? My raster package is v2.5-8.


Solution

  • That is a bug that needs to be fixed in the raster package, but here is a work around:

    row.names(nepal) <- '1'
    border_values <- extract(r, nepal, sp=TRUE, fun=median, match.ID=FALSE)
    

    or more generally, (if you have multiple features)

    row.names(nepal) <- as.character(1:length(nepal))