3

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

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
canderson156
  • 1,045
  • 10
  • 24

2 Answers2

2

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)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
0
library(terra)
library(tidyverse)

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

plot(x)

plot(x) after reclass

reclassified <- cats(x)[[1]] %>%
  mutate(label_reclass = forcats::fct_collapse(cats(x)[[1]]$label,c="b"))

x <- categories(x, layer=1, value=reclassified, active=2)

plot(x)

plot(x) after

levels(x)

[[1]]
  value label_reclass
1     1             a
2     2             c
3     3             c
Cazz
  • 83
  • 7