Simon Rolph
Simon Rolph

Reputation: 51

Setting values of layer of SpatRaster

I have a raster with 12 layers, one for each month. I want to be set the values of certain cells (which I have already got the IDs of) but I only want to set those values on one layer.

Here is a raster

test_raster <- rast(vals= 0,
                    nrows=1500,
                    ncols=2000,
                    xmin=xmin,
                    xmax=xmax,
                    ymin=ymin,
                    ymax=ymax,
                    nlyrs= 12,
                    names = tolower(month.abb),
                    crs="+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs ")

Here are the IDs of the cells I'd like to carry out the replacement/assignment on and the values I would like to replace them with

cells_to_replace_values <- c(1:300)
values_for_replacement <- sample(1:300,300)

I can easily replace the values in every layer successfully

> test_raster[cells_to_replace_values] <- values_for_replacement
> test_raster
class       : SpatRaster 
dimensions  : 1500, 2000, 12  (nrow, ncol, nlyr)
resolution  : 100, 100  (x, y)
extent      : 350000, 550000, 250000, 4e+05  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs 
source      : memory 
names       : jan, feb, mar, apr, may, jun, ... 
min values  :   0,   0,   0,   0,   0,   0, ... 
max values  : 300, 300, 300, 300, 300, 300, ...

But I only want assign to one month, January. I have tried 2 approaches but with these errors:

Attempt 1

> test_raster[cells_to_replace_values]["jan"] <- values_for_replacement
Error: [setValues] values must be numeric, integer, logical, factor or character

Attempt 2

>subset(test_raster,1)[cells_to_replace_values] <- values_for_replacement
Error in subset(test_raster, 1)[cells_to_replace_values] <- values_for_replacement : 
could not find function "subset<-"

Could someone advise how I should do this? Thanks!

Upvotes: 1

Views: 1461

Answers (1)

Simon Rolph
Simon Rolph

Reputation: 51

I eventually found the correct configuration to be able to do this:

test_raster[["jan"]][cells_to_replace_values] <- values_for_replacement

The layer name had to be in [[ ]] and then followed by the cell IDs

Upvotes: 3

Related Questions