简体   繁体   中英

Example in the 'rasterize' documentation does not work?

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', ie:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM