Reputation: 6761
I've got a rasterbrick, with layers of climate data on islands, surrounded by NA ocean cells. I'd like to set a few of the ocean cells to the value of the coast nearby. Having a surprising amount of trouble doing this. In my mind the code should be something like below, but I run out of memory. The rasters are large approx 2500x2500.
# dummy stack with three layers
slogo <- stack(system.file("external/rlogo.grd", package="raster"))
# let's say cell 5 is the one I want to change
newvals <- 1000*(1:3)
for(i in 1:nlayers(slogo)) slogo[[i]][5] <- newvals[i]
Subsequent step will be writing the rasters to separate ascii files; so an alternative hacky solution might be snipping into the text file and replacing single values...
EDIT:
Perhaps there's a solution someone can recommend by resetting memory allocation limits? Here's the error message I show after running on my large raster.
Error: cannot allocate vector of size 504.1 Mb
In addition: Warning messages:
1: In readBin(raster@file@con, what = dtype, n = nc, dsize, dsign, :
Reached total allocation of 3979Mb: see help(memory.size)
2: In readBin(raster@file@con, what = dtype, n = nc, dsize, dsign, :
Reached total allocation of 3979Mb: see help(memory.size)
3: closing unused connection 4 (C:\Users\jcw\AppData\Local\Temp\R_raster_jcw\r_tmp_2015-08-16_130255_2000_11926.gri)
4: In getBilData(object, r = startrow, nrows = nrows, c = startcol, :
Reached total allocation of 3979Mb: see help(memory.size)
5: In getBilData(object, r = startrow, nrows = nrows, c = startcol, :
Reached total allocation of 3979Mb: see help(memory.size)
6: In getBilData(object, r = startrow, nrows = nrows, c = startcol, :
Reached total allocation of 3979Mb: see help(memory.size)
7: In getBilData(object, r = startrow, nrows = nrows, c = startcol, :
Reached total allocation of 3979Mb: see help(memory.size)
Upvotes: 2
Views: 992
Reputation: 47071
You can use the raster::update
function to change values in raster files on disk (do make backups!)
Upvotes: 0
Reputation: 3485
You were pretty close, it's just an indexing issue:
library(raster)
# dummy stack with three layers
slogo <- brick(system.file("external/rlogo.grd", package="raster"))
## Check values of all three bands at cell 5:
slogo[5]
Yields:
red green blue
[1,] 255 255 255
## Set values of all three bands to zero:
slogo[5][1:3] <- 0
slogo[5]
Yields:
red green blue
[1,] 0 0 0
An alternative that might get the OP past the memory issues of processing all of the bands at once:
## Alternatively, load each band into memory separately, do the
## replacement and write each band back to disk as a separate GeoTiff:
for (i in 1:nbands(slogo)) {
r <- raster(slogo, layer=i)
r[5] <- 0
writeRaster(r, file=paste0("band_", i, ".tif"), format="GTiff")
}
Upvotes: 1