Search code examples
rreplaceraster

Changing cell values from a raster


I have raster cell values with 5 digits, but I need to get rid of the first one, for instance, if the the cell value is "31345" I need to make it "1345". I am trying to use the calc() function from the raster package to do that by subtracting different numbers from based on the raster cell value (since they are all numbers), like this:

correct.grid <- calc(grid, fun=function(x){ifelse(x < 40000, x-30000,
                                          ifelse(x > 40000 & < 50000, x-40000,
                                                 ifelse(x > 50000 & < 60000, x-50000,
                                                        ifelse(x > 60000, x-60000, 0)))))})

I guess this is probably a terrible approach to the problem (I am not really good at programming), still, I ran into an error because I am using ">" and "<" inside the function I am guessing. Any ideas on how to make these "ifelse"s to work or maybe a smarter approach to the problem?

This is a piece of the unique values in my data if it helps:

> unique(grid)
  [1] 30057 30084 30207 30230 30235 30237 30280 30283 30311 30319 30320 30326 30350 30351 30352 30360
 [17] 30384 30396 30415 30420 30447 30449 30452 30456 30478 30481 30497 30507 30522 30560 30562 30605
 [33] 30606 30612 30638 30639 30645 30654 30657 30658 30662 30665 30678 30682 30701 30707 30714 30736
 [49] 30740 30743 30749 30750 30823 30824 30841 30852 30862 30892 30896 30898 30915 30920 30928 30934
 [65] 30956 30962 30978 30986 30998 31021 31022 31031 31042 31053 31055 31081 31085 31092 31097 31099
 [81] 31114 31115 31122 31126 31129 31130 31131 31141 31157 31168 31171 40019 40026 40075 40197 40217
 [97] 50342 50360 50379 50496 50720 50725 50732 50766 50798 50837 51073 51092 51397 53096 53110 53117
[113] 53118 53120 53124 60003 60005 60041 60485 60516 60655 60661 60825 61039 61174 61185 61187 61210
[129] 61221 61224 61227 61259 61287 61289 61290 61295

Solution

  • If you just want to remove the leftmost digit of each value, how about this:

    First, let's load a raster object to work with:

    library(raster)
    
    # Load a raster object to work with
    grid = system.file("external/test.grd", package="raster")
    grid = raster(grid)
    
    # Set up values to be whole numbers
    values(grid) = round(values(grid)*100)
    

    Now, remove the leftmost digit from every value in the raster:

    values(grid) = as.numeric(substr(values(grid), 2, nchar(values(grid))))
    

    Note that a value with one or more zeros after the leftmost digit will get shortened by more than one digit. For example, 60661 will become 661 and 30001 will become 1.