1

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)
5

getmode is called with two arguments in case you want to handle missing values in your custom function. Rewrite it to accept extra arguments:

getmode <- function(v,na.rm) {
uniqv <- unique(v)
uniqv[which.max(tabulate(match(v, uniqv)))]
}   

that should fix that problem (and reveal the next one...)

2
  • Thank you! Next error is: Error in setValues(rs, vv) : values must be numeric, integer, logical or factor however, val is already a factor class. any ideas?
    – Jack_d
    Mar 29 '20 at 22:24
  • @Jack_daniels Please ask a new question for the "Next error". That way we start to build another Q&A with another new clear question likely to result in another clear answer.
    – PolyGeo
    Mar 29 '20 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.