rterrarasterize

`terra::rasterize`: points with categorical values gets transformed to numeric


I want to rasterize categorical values from a shapefile of points to a raster. I used to be able to do this, but my code is no longer working.

Here's a reproducible example:

points <- tibble::tribble(
  ~x,~y, ~cat,
  -34.125, -58.162,'a',         
  -34.225, -58.462,'b',         
  -34.325, -58.362,'c',         
  -34.425, -58.662,'d',         
  -34.525, -58.762,'e',         
  -34.625, -58.862,'f'
)
points <- st_as_sf(points, coords = c("x", "y"), crs = 4326)
polygons <- st_buffer(points, dist = 0.1) 

v1 <- vect(points)
v2 <- vect(polygons)
r <- rast(v1, res=0.1)

rasterize(v1, r, 'cat')
rasterize(v2, r, 'cat')

As a result, I get:

class       : SpatRaster 
dimensions  : 7, 5, 1  (nrow, ncol, nlyr)
resolution  : 0.1, 0.1  (x, y)
extent      : -34.625, -34.125, -58.862, -58.162  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326) 
source(s)   : memory
name        : cat 
min value   :   0 
max value   :   5

and

class       : SpatRaster 
dimensions  : 7, 5, 1  (nrow, ncol, nlyr)
resolution  : 0.1, 0.1  (x, y)
extent      : -34.625, -34.125, -58.862, -58.162  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326) 
source(s)   : memory
categories  : cat 
name        : cat 
min value   :   a 
max value   :   e 

So, it works for polygons but not for points. I want that the char value is returned, not the numeric value.

Also, I used to be able to use first as a function, but this seems no longer supported.

Thanks!


Solution

  • You can set the levels after rasterizing:

    p <- data.frame(
        x = c(-34.125, -34.225, -34.325, -34.425, -34.525, -34.625), 
        y = c(-58.162, -58.462, -58.362, -58.662, -58.762, -58.862), 
        cat = factor(c("a", "b", "c", "d", "e", "f")))
    
    library(terra)
    #terra 1.7.78
    v <- vect(p, c("x", "y"), crs = "epsg:4326")
    r <- rast(v, res=0.1)
    x <- rasterize(v, r, 'cat')
    
    levels(x) <- data.frame(id=0:5, cat=levels(p$cat))
    x
    #class       : SpatRaster 
    #dimensions  : 7, 5, 1  (nrow, ncol, nlyr)
    #resolution  : 0.1, 0.1  (x, y)
    #extent      : -34.625, -34.125, -58.862, -58.162  (xmin, xmax, ymin, ymax)
    #coord. ref. : lon/lat WGS 84 (EPSG:4326) 
    #source(s)   : memory
    #categories  : cat 
    #name        : cat 
    #min value   :   a 
    #max value   :   f