Tpellirn
Tpellirn

Reputation: 796

How to replace different values in raster?

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!!

Upvotes: 0

Views: 60

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

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)]

Upvotes: 2

Related Questions