fasterize icon indicating copy to clipboard operation
fasterize copied to clipboard

"ratify" a character field

Open mdsumner opened this issue 6 years ago • 1 comments

Consider using raster's ratify for character and factor columns? (raster::rasterize doesn't currently)

(I'd like to have a go at this, but not today so I just want to record what I described already! )

Raster allows for a classification with a factor-like mechanism, called ratify - "raster attribute table".

This could allow setting field = to a character-column, and also better handle the output when field is a factor.

Currently an error if field is a factor (so related to #20)

library(sf)
example(st_read)
## create character column 
nc$chr <- levels(nc$NAME)[nc$NAME]
library(fasterize)
fasterize(nc, raster(nc, nrows = 300, ncols = 600), field = "chr")
#Error in fasterize(nc, raster(nc, nrows = 300, ncols = 600), field = "chr") : 
#  Not compatible with requested type: [type=character; target=double].

It's a little awkward, but we can set up a factor column from a character field, fasterize, and then apply the levels classification.

## a workaround at the R level is
field <- "chr"
nc$field <- factor(nc[[field]])
r <- fasterize(nc, raster(nc, nrows = 300, ncols = 600), field = "field")
## put the classifications on with ratify/levels
r  <- ratify(r)
rat <- levels(r)[[1]]
rat[[field]] <- levels(nc$field)
levels(r) <- rat

mdsumner avatar Apr 18 '18 08:04 mdsumner

FTR, in #26, I include an alternative version of the R fasterize() wrapper. It implements this feature as part of a more general upgrade of fasterize()'s handling of factor and numeric rasters and feature fields. If there's any interest, I'll eventually submit it as a pull request, but wanted to first make it available for review and possible improvement by others.

JoshOBrien avatar May 13 '19 16:05 JoshOBrien