rrasterqgis

Raster reclassify generating wrong values


I am trying to reclassify a raster object of altitude, in order for values >= 2300 to become 1 and < 2300 to become 0. (the object is Worldclim elevation 30s) I tried it on QGIS Raster calculator

"wc2.1_30s_elev@1" >= 2300

and the map it yielded was strange (strange negative numbers, and no apparent differentiation between > or < 2300. However, when I manually customized the labels to be 0 or 1, the map appeared to be correct. Also, the "Identify features" tool showed the correct values. But when I used this layer for an operation in Raster Calculator (my next step), the resulting layer showed the same problems.

So, I tried to do it in R. At first I tried

r[r < 2300] <- 0
r[r >= 2300] <- 1

But the same problem came up. So I tried raster::reclassify

reclass_df <- c(0, 2300, 0,
            2301, 6651, 1)
reclass <- matrix(reclass_df,
                ncol = 3,
                byrow = TRUE)

r_reclassif <- reclassify(r, reclass)

And the strange values were not there anymore, but still the map showed no apparent differentiation between > or < 2300.

At first, it was only a visual problem. Plotting with a specified sequence of breaks seemed to do the task.

plot(r, col = color_palette, breaks = seq(0, 0.0109, length.out = 101))

But I need to do another step: a terra::xyFromCell using the raster as a probability argument. Then, the strange values and lack of discrimination between altitudes become a problem.

Could somebody help? I have no idea what's going on.


Solution

  • Example data

    library(terra)
    r <- rast(system.file("ex/elev.tif", package="terra"))
    

    Which areas are higher than 400m? All you have to do is

    x <- r > 400
    plot(x)
    

    Note that TRUE is equivalent to 1 and FALSE is equivalent to 0.

    Alternatively, you can do

    y <- classify(r, rbind(c(-Inf, 400, 0), c(400, Inf, 1)))
    
    # or 
    
    z <- ifel(r < 400, 0, 1)
    

    I note that in your use of raster::reclassify, you assume that zero is the lowest possible elevation. That is not correct.