"external/test.grd"
isn't the best way to test this. Is a very small raster, so results can't be applied in a large raster.
Here I present a comparison with 4 different approaches, the file used is a mosaic of 12 tiles of ALOS DEM 30m (size per tile: 1x1 degree). Options a
and b
are the most suitable for small rasters, let's see if they are good for big ones:
library(raster)
library(microbenchmark)
r <- raster('~/path/to/mosaic.tif')
NAvalue(r) <- -9999
r <- setMinMax(r)
plot(r)

plot(is.na(r))

microbenchmark(a = r[is.na(r[])] <- 0,
b = values(r)[is.na(values(r))] <- 0,
c = raster::mask(r,is.na(r),maskvalue = 1, updatevalue = 0),
d = reclassify(r, cbind(NA, NA, 0), right=FALSE),
times = 100L)
## Unit: seconds
## expr min lq mean median uq max neval cld
## a 1.653149 1.898718 2.031415 1.971430 2.120584 3.352690 100 ab
## b 1.707620 1.938079 2.126679 2.089398 2.235046 3.033048 100 b
## c 4.362750 5.176214 5.413074 5.471538 5.660152 6.599903 100 c
## d 1.424628 1.791048 1.935061 1.860629 2.044008 2.753409 100 a
Option d
seems to be a slightly efficient, but there isn't significant differences in this case. Maybe in bigger rasters could be.