I have a large raster with many unique values and a complex attribute table. I would like to create a much simpler raster that only has the values of one level, a level which only has values 0-2.
Say I have a raster, but am really only interested in the variable y:
library(terra)
r <- rast(nrows=3, ncols=3)
values(r) <- 1:9
y_table <- data.frame(id=1:9, y=c(0,0,1,0,1,1,2,2,2))
levels(r) <- y_table
Is there a way to create a new raster that effectively substitutes the y level for the values? So rather than
levels(r)
id y
1 1 0
2 2 0
3 3 1
4 4 0
5 5 1
6 6 1
7 7 2
8 8 2
9 9 2
values(r)
y
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
I get to
levels(r_converted)
[1] ""
values(r_converted)
lyr.1
[1,] 0
[2,] 0
[3,] 1
[4,] 0
[5,] 1
[6,] 1
[7,] 2
[8,] 2
[9,] 2
I clumsily have tried both classify and subst:
testc <- classify(r, rcl=matrix(c(0:2, 0:2), ncol=2), right=NA)
tests <- subst(r, 0:2, 0:2)
but neither changes the values themselves.


Using r and r2, y_table and y_table2, but think this is what you're after:
see
?terra::factorsand your categories become multidimensional, your df has move than 2 columns.Edit. I think both @grzegorz-sapjaszko and @geoffery both serve you better in advising
classifyas your rasters are likely far larger than your reprex. You don't say above that you 'need' factors and it seems more a way of simplifiying. This could readily be achieved by preparing a 'from-to' matrix that represents your many classes. So a bigger raster and classifyIt really comes down to your data and needs. If you already have
factorsyou'd useterra::subst.