Function to return values (velox raster)

1.2k Views Asked by At

I'm using the new velox extract function to speed up raster extraction by shapefiles.

The old raster package's extract function by default returned a list of cell values, for example when you use the below format:

val.list <- raster::extract(raster, shapefile)

The new velox package requires a fun= argument and I can't for the life of me get it to return the values:

vx.raster <- velox(raster)
vx.vals <- vx.raster$extract(shapefile, fun=??????)

I have tried:
fun=values (returns error Error during wrapup: unable to find an inherited method for function 'values' for signature 'numeric'
fun=function(x){values(x)} (same error as above)

I get fun=sum, fun=mean to work just fine. Whats up with values? Am I just missing something obvious about a numeric vector and returning a values list (which I feel is the most likely case)?

Thank you!

2

There are 2 best solutions below

0
Dominika On

Simply try this snippet

vx.raster$crop(shapefile).
0
hunzikp On

The development version of velox (on github) now allows returning 'raw' raster values from a VeloxRaster_extract query. Just set the fun argument to NULL.

Here's an example:

library(devtools)
install_github('hunzikp/velox')
library(velox)

## Make VeloxRaster with two bands
set.seed(0)
mat1 <- matrix(rnorm(100), 10, 10)
mat2 <- matrix(rnorm(100), 10, 10)
vx <- velox(list(mat1, mat2), extent=c(0,1,0,1), res=c(0.1,0.1),
        crs="+proj=longlat +datum=WGS84 +no_defs")

## Make SpatialPolygons
library(sp)
library(rgeos)
coord <- cbind(0.5, 0.5)
spoint <- SpatialPoints(coords=coord)
spols <- gBuffer(spgeom=spoint, width=0.5)

## Extract
vx$extract(sp=spols, fun=NULL)$buffer
#             [,1]        [,2]
# [1,]  1.27242932  0.04658030
# [2,]  0.41464143 -1.13038578
# [3,] -1.53995004  0.57671878
#  etc....