specifying labels using cut() on raster

Viewed 39

Suppose I have a the following raster:

library(raster)    
r <- raster(ncols=36, nrows=18)
values(r) <- rnorm(ncell(r)) 

I can discretise its values using cut():

breaks <- -2:2 * 3
rc <- cut(r, breaks=breaks)

However, when i try to specify labels e.g., A, B, C, etc

rc <- cut(r, breaks=breaks, labels = c("A", "B", "C", "D", "E"))

it returns the following error.

Error in cut.default(getValues(x), breaks = breaks, labels = FALSE,
...) :    formal argument "labels" matched by multiple actual
arguments

I tried googling the error message but no luck. Any ideas what is going wrong?

2 Answers

Firstly, you only have 5 breaks, so you can only have 4 labels. Secondly, you could use cut on the data of the raster rather than the whole raster object:

rc <- r
rc[] <- cut(rc[], breaks = breaks, labels = c("A", "B","C","D"))
rc
#> class      : RasterLayer 
#> dimensions : 18, 36, 648  (nrow, ncol, ncell)
#> resolution : 10, 10  (x, y)
#> extent     : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#> crs        : +proj=longlat +datum=WGS84 
#> source     : memory
#> names      : layer 
#> values     : 1, 4  (min, max)
#> attributes :
#>  ID VALUE
#>   1     A
#>   2     B
#>   3     C
#>   4     D

This is how I would do that, using terra:

library(terra)    
r <- rast(ncols=36, nrows=18)
values(r) <- rnorm(ncell(r)) 
breaks <- -2:2 * 3

rc <- classify(r, breaks)

levels(rc)
#[[1]]
#[1] "(-6–-3]" "(-3–0]"  "(0–3]"   "(3–6]"  

levels(rc) <- c("A", "B", "C", "D")

rc
#class       : SpatRaster 
#dimensions  : 18, 36, 1  (nrow, ncol, nlyr)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
#source      : memory 
#name        : layer 
#min value   :     A 
#max value   :     D 
Related