Search code examples
rraster

reclass values of multiple rasters with their names in R


I'm trying to make a reclassification of several raster files with R. My raster files contain species ranges with the values of the total range in the occurring cells. The other cells have NoData. The files have their rank as name (1,2,3...). Now I try to reclass the values of the cells where species occurs with the Rank. I tried with for looping the reclassify function without success... thanks in advance!


Solution

  • Let's say you have one raster representing the presence/absences of a single species. You also know the area extent and the range (expressed as occurrences) of this particular species. For each cell where this species is present you've filled it with the total occurrences.

    Lets say this species was detected on 50 out of 400 cells.

    The species occurrence expressed by presence on 50 random cells.

    e1 <- extent(0,10,0,10)
    r1 <- raster(extent(0,10,0,10))
    res(r1) <- 0.5
    r1[1:ncell(r1)] <- NA
    r1[sample(ncell(r1), 50, rep = F)] <- 50    
    plot(r1)
    

    r1

    But you may have this rasterLayer as a image file, stored at your disk and named with a rank of the species.

    There are several ways to replace values in a rasterLayer. If for this particular species the rank is 1, you can replace the range by rank with

    r1[!is.na(r1)] <- 1
    

    r1 reclassified

    If you want to lop over your file folder try this:

    wdata <- '.../R/Stackoverflow/21876858' # your local folder
    f.reclass <- function(x=x){
      files <- list.files(file.path(wdata), all.files = F) # list all files from a given driver folder
      # Assuming TIF images, List files from wdata folder
      ## Change below if using any other format
      ltif <- grep(".tif$", files, ignore.case = TRUE, value = TRUE) 
      stkl <- stack()
      for(i in 1:length(ltif)){
        x <- raster(file.path(wdata, ltif[i]),
                    package = "raster", varname = fname)
        rank <- as.numeric(sub("*.tif", "", ltif[i]))
        # Change also here if not tif
        stopifnot(is.numeric(rank)) # check for numeric
        x[!is.na(x)] <- rank
        stkl <- addLayer(stkl, x)
      }
      stkl
    }
    
    spreclass <- f.reclass(x=x)
    

    You'll get a rasterStack object with your reclassified rasterLayers. your can unstack them, export, manipulate...