I have a raster Z with elevation values (0, 0.12, 2.12), which I created myself in R. I want to produce a land-use raster from these elevation values, i.e. if Z<0.12, I assign land-use class 1 to it, if Z== 0.12, I assign land-use class 2 and if z>0.12, land-use class 3 and so on. I realized that using the method


only works for two cases. If there are 3 cases (like in my case), the whole raster just fills up with the values from the last expression, in this case, 3.

What can I do to prevent this behaviour or is there any other method to replace the values and not have this effect?


You must invert your order:

Z <- runif(100, 0, 2)


Your problem was due to in the first sentence (Z[Z<0.12]<-1) you made values become 1. Then in the last sentence you looked for everyone >0.12 (1 included).

  • 2
    This works perfectly. Exactly what I needed. Unfortunately my reputation is too low to upvote your answer. Thanks – M Terry Sep 3 at 14:32

You could use reclassify to do this:

Z2 = reclassify(Z, c(-Inf, .1, 1, .1,.14, 2, 2.1, 2.2,3))

quick cross-tab check:

> table(Z2[],Z[])

     0 0.12 2.12
  1 10    0    0
  2  0    5    0
  3  0    0   10

That vector of values argument is treated as a matrix of 3 columns, filled by rows:

     [,1] [,2] [,3]
[1,] -Inf 0.10    1
[2,]  0.1 0.14    2
[3,]  2.1 2.20    3

such that any values between the first and second column values get the third column. I've constructed it such that the first and second column bracket the three values in your data.

Doing exact comparisons with floating point values (eg Z[Z==0.12]) is a bad idea, see R FAQ 7.31 for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.