hunzikp / velox

https://hunzikp.github.io/velox/
119 stars 23 forks source link

VeloxRaster_extract "Error in out[p, k] <- fun(valmat[, k]) " #11

Closed AronBoettcher closed 7 years ago

AronBoettcher commented 7 years ago

"Error in out[p, k] <- fun(valmat[, k]) : number of items to replace is not a multiple of replacement length"

I'm trying to do table statistics for a velox raster object using "VeloxRaster_extract" It would be nice to be able to retrieve either the values from the extraction directly or be able to pass into "VeloxRaster_extract" a function that returns more than one value.

Sample code something like.. s.x <- velox(some.stack) s.p <- spdf(some.spdf) s.x$extract(s.p, fun=table)

throws the error. The documentation says fun must be function accepting a numeric vector as its sole input, so "table" should work. Issue is that the function expects to only return one value as its output.

hunzikp commented 7 years ago

The extract function now allows extracting 'raw' (non-aggregated) raster values, see #8. You can now summarize the raster values with the table function as follows:

## Make VeloxRaster with two bands
set.seed(0)
mat1 <- matrix(rpois(100, 1), 10, 10)
mat2 <- matrix(rpois(100, 1), 10, 10)
brk <- brick(raster(mat1), raster(mat2))
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
coord <- matrix(c(0,0,1,1), 2, 2, byrow = TRUE)
spoint <- SpatialPoints(coords=coord)
spols <- gBuffer(spgeom=spoint, width=0.2, byid = TRUE)

## Extract raw values as lists
vx.elist <- vx$extract(sp=spols, fun = NULL)

## Make table (as DF) for each raster band
vx.mat <- do.call('rbind', vx.elist)
apply(vx.mat, 2, function(x) as.data.frame(table(x)))