Reputation: 587
I use the rasterize
function from the raster
package quite often. As indicated in its documentation, any custom function being used through the fun
argument needs to accept an na.rm
argument. This generally means that custom functions are written with the 'dots', i.e.:
funA <- function(x,...)length(x)
However, a second proposed approach is to write a custom function with an explicit na.rm
argument. The example that is given in the documentation is:
funB <- function(x, na.rm) if (na.rm) length(na.omit(x))
However, this does not seem to work! This example, in which some random points are distributed across a grid fails:
# Create a grid
grid <- raster(ncols=36, nrows=18)
# Scatter some random points within the grid
pts <- spsample(as(extent(grid), "SpatialPolygons"), 100, type = "random")
# Give them a random data field
pts <- SpatialPointsDataFrame(pts, data.frame(field1 = runif(length(pts))))
# Try rasterize
rasterize(pts, grid, field = "field1", fun = funB)
Is there something I'm missing here?
Thanks! Andrew
Upvotes: 1
Views: 99
Reputation: 3176
You were close.
Function B should look like:
funB <- function(x, na.rm=T) if (na.rm) length(na.omit(x))
rasterize(pts, grid, field = "field1", fun = funB)
the na.rm
argument as to be TRUE
or FALSE
, adding a default value deals with the problem.
What still annoys' me is that this:
funB <- function(x, na.rm) if (na.rm) length(na.omit(x))
rasterize(pts, grid, field = "field1", fun = funB, na.rm=TRUE)
should work but it doesn't. It's maybe something with the raster package.
Upvotes: 1