Here is a reproducible example for your problem:
library(terra)
set.seed(123)
r1 <- rast(matrix(round(runif(400, 0, 100)), 20, 20))
plot(r1)
r2 <- rast(matrix(round(runif(400, 0, 10)), 20, 20))
r3 <- rast(matrix(round(runif(400, 30, 70)), 20, 20))
Even if I wasn't able to reproduce your warning code, I think your problem is in your interpretation of this call: r2== 6 & r3>= 40 & r3 <= 60
. This line produces a raster:
r2== 6 & r3>= 40 & r3 <= 60
class : SpatRaster
dimensions : 20, 20, 1 (nrow, ncol, nlyr)
resolution : 0.05, 0.05 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
coord. ref. :
source : memory
name : lyr.1
min value : 0
max value : 1
An therefore making this call r1[r2== 6 & r3>= 40 & r3 <= 60]
produce a dataframe:
str(r1[r2== 6 & r3>= 40 & r3 <= 60])
'data.frame': 17 obs. of 1 variable:
$ lyr.1: num 2 2 2 2 2 2 2 2 2 2 ...
You don't want that because length
of a 1 column data.frame = 1 and because you can't do value substitution with a data.frame.
Try this instead:
pixel_to_change <- values(r2== 6 & r3>= 40 & r3<= 60) == 1
r1[pixel_to_change] <- sample(2:4, sum(pixel_to_change), replace = T)
It may be what your are looking for.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…