Search code examples
rdplyrrastermagrittr

Change raster values within a %>% pipe


I have a raster where the data I am interested in (a species presence) value is 1, and the rest is either 0 (absence) or NA. I am trying to use magrittr and dplyr and, inside a pipe, I would like to change all 0 values to NA, so I can later trim the raster and get the min and max coordinates of the data where the species is (value = 1)

However, changing value 0 to NA is something I would normally do with something like:

raster[values(raster) == 0] <- NA

I have trouble doing that kind of operations, "from right to left", with magrittr (can they be done?). I learnt that names() <- could be exchanched by setNames(), or that you could use the `` symbols to use operation signs (i.e.: raster %>%*(raster2) to multiply by another raster)`

Is there a way to get an equivalent result working with the pipes?

Thanks!!!


Solution

  • One way is to use raster::reclassify:

    library(raster)
    library(magrittr)
    r <- raster(matrix(0:3, 2))
    
    r %>% reclassify(c(0, 0, NA), right=NA)
    

    This may also be ever so slightly faster than @MrFlick's nice zero_to_na suggestion (on bigger rasters, anyway!), in case you're doing a lot of this stuff. The tradeoff is that it's clearly less elegant.

    r <- raster(matrix(rbinom(1e6, 1, 0.5), 1e3))
    microbenchmark::microbenchmark(
        this=r %>% reclassify(c(0, 0, NA), right=NA),
        that=r %>% zero_to_na)
    
    Unit: milliseconds
     expr      min       lq     mean   median       uq      max neval cld
     this 21.77720 22.85843 32.48079 25.05024 26.05527 168.1101   100  a 
     that 29.46083 31.37556 56.32881 33.48350 38.05476 202.8740   100   b