I have a series of spatial data points that I want to convert to a raster using the R function rasterize. The data I want represented is a factor value, so I want to represent the most frequently occuring value for each raster cell.
I have tried to write a funtion to get the mode, but it fails.
getmode <- function(v) {
uniqv <- unique(v)
uniqv[which.max(tabulate(match(v, uniqv)))]
}
#run rasterize
test <- rasterize(best, rast, best$val, fun = getmode)
results in this error:
Error in FUN(X[[i]], ...) : unused argument (na.rm = na.rm)
Here is a minimal self-contained reproducible example:
library(raster)
r <- raster(ncols=20, nrows=10)
n <- 1000
set.seed(123)
x <- runif(n) * 360 - 180
y <- runif(n) * 180 - 90
xy <- cbind(x, y)
v <- sample(10, n, replace=TRUE)
Now add ...
to your function (see the documentation entry under fun
in ?rasterize
):
getmode <- function(v, ...) {
uniqv <- unique(v)
uniqv[which.max(tabulate(match(v, uniqv)))]
}
And use it:
m <- rasterize(xy, r, v, getmode)