geotheory
geotheory

Reputation: 23630

"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.

Upvotes: 0

Views: 178

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47061

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))

Upvotes: 2

Related Questions