Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reclassify a categorical raster in terra using category names

I'd like to be able to merge two categories in a categorical raster. The only solution I've figured out so far uses the level index number, not the name of the category. How could I do this using the name of the category?

library(terra)
m <- matrix(rep(c("a", "b", "c"), each = 3), nrow = 3, ncol = 3)
x <- rast(m)

x[x$lyr.1 == "c"]

m2 <- matrix(c("a", "a", "b", "b", "c", "b"), nrow = 3, ncol = 2, byrow = TRUE)

test <- classify(x, m2)
#doesn't work with category names

test <- subst(x, "c", "b")
#doesn't work with category names

test <- subst(x, 2, 1)
#works with category index

like image 327
canderson156 Avatar asked Oct 12 '25 18:10

canderson156


1 Answers

Example data

library(terra)
m <- matrix(rep(c("a", "b", "c"), each = 3), nrow = 3, ncol = 3)
x <- rast(m)
m2 <- matrix(c("a", "a", "b", "b", "c", "b"), nrow = 3, ncol = 2, byrow = TRUE)

With the current version of terra you can do either

test1 <- subst(x, "c", "b")

or

test2 <- subst(x, 2, 1, raw=TRUE)
like image 196
Robert Hijmans Avatar answered Oct 14 '25 11:10

Robert Hijmans