TWest
TWest

Reputation: 824

How to replace NA in a large raster with values from another raster in R?

I have two large raster images (30,000 x 30,000), one for the year 2000 another for 2005. I want to replace the pixels with NA in the 2000 raster with their respective non-NA values from the 2005 raster. Here is an example:

r1 <- raster(ncols=36, nrows=18)
r1[] <- 1:ncell(r1)
plot(r1)
r2 <- raster(ncols=36, nrows=18)
r2[] <- 1:ncell(r2)
r2[r2<300] <- NA
plot(r2)

In this example I would like to replace the NA's in "r2" by their respetive values in "r1". I tried the command "cover()" in R but that one does not complete "r2," rather it returns the info that is missing in "r2" but present in "r1":

r2.fix <- cover(r2, r1)
plot(r2.fix)

Any ideas on how the job done? Thank you in advance.

UPDATE: The problem with this solution:

r2[is.na(r2)] <- r1[is.na(r2)]

Is that it does not work with large rasters. R returns the following error:

Error: cannot allocate vector of size 2.6 Gb
In addition: Warning messages:
1: In order(cells[, 2]) :
  Reached total allocation of 16080Mb: see help(memory.size)

Upvotes: 0

Views: 891

Answers (1)

Arkadii Kuznetsov
Arkadii Kuznetsov

Reputation: 479

I can reproduce your problem only with large raster.
I have Error: cannot allocate vector of size 6.7 Gb with 16GB RAM.
You need to change the chunksize in the Session options.

From Introduction to the ’raster’ package

The options chunksize and maxmemory determine the maximum size (in number of cells) of a single chunk of values that is read/written in chunk-by-chunk processing of very large files.

Upvotes: 1

Related Questions