rrasterr-sfr-stars

sf and stars: polygonize categorical raster


I'd like to draw the raster countour (l) just only for the "target" categorical in x raster without considering NA values. I try to do:

# Packages
library(stars)
library(sf)

#Vectorizing a raster object to an sf object
tif = system.file("tif/L7_ETMs.tif", package = "stars")
x = read_stars(tif)[, 1:50, 1:50, 1:2]
x[[1]] = round(x[[1]]/5)
x[[1]] = ifelse(x[[1]]<10,NA,"target")
str(x[[1]])

#Polygonizing
l =  st_contour(x)
plot(l[1])
Error in CPL_write_gdal(mat, file, driver, options, type, dims, from,  : 
  Not compatible with requested type: [type=character; target=double].

But, doesn't work. Please, any help with it?

Thanks in advance,

Alexandre


Solution

  • There are several errors with your script, first, st_contour is indicating that it is not compatible with the character type (referring to the "target" string you set in the raster). Secondly, I would suggest using the breaks argument inside st_contour to set the target value for which you wish to obtain the contours. Additionally, you might want to use x[rule] <- NA to mask certain values in the raster. I made other modifications to your code that might help:

    # Let's stay with only the first band, indicated in the final dimension
    x = read_stars(tif)[, 1:50, 1:50, 1]
    x = round(x/5)
    # Calculate the min and max of the raster values
    purrr::map(x, min)
    # 10
    purrr::map(x, max)
    # 28
    # Mask values lower than 10
    # However, this does not make any change, because the lowest value is 10
    x[x<10] <- NA
    # Take a look at the image
    plot(x)
    
    # Obtain the contours
    l =  st_contour(x, 
                    # Remove NA
                    na.rm = T,
                    # Obtain contour lines instead of polygons
                    contour_lines = TRUE,
                    # raster values at which to draw contour levels
                    breaks = 12)
    # Plot the contours
    plot(l)