0

if I have this raster

       r1 <- raster(nrow=10, ncol=10)
       vv=c(1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5,1:5)
       values(r1) <- vv

How to do this:

  replace    by
   3           1
   5           2
   2           3
   4          5
    1           4

I know we can do

r1[r1==3]=1    but then it will problematic with values already = 1 (that I need to replace by 4!!
Tpellirn
  • 660
  • 4
  • 11
  • Does this answer your question? [How to replace multiple values at once](https://stackoverflow.com/questions/50898623/how-to-replace-multiple-values-at-once) – Basti May 10 '22 at 13:05

1 Answers1

2

In this particular case (where current values are contiguous low-valued integers starting at 1), you can use the current values as indexes of the replacement vector:

r1[] <- c(4, 3, 1, 5, 2)[r1@data@values]

A more general solution if you have both replace and by defined is

r1[] <- by[match(r1@data@values, replace)]
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87