I would like to change all the non-NA cell values based on the cells longitude. For instance, any cell that had a non-NA value and a longitude greater than x would have the value replaced with y. I have found a way to do this based on the column index, but it is a fiddly and imprecise.
Here is an example of what I have managed to create based on the column index.
#Reading in a raster from the terra package
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
plot(r)
And I would like to change all the non-NA (i.e., all the cells that already have a colour in the above plot) that have a longitude greater than say 6, to have a new value of 500. Here is my solution based on column index:
r2 <- r2
#Here I have fiddled with the column index to arrive at a longitude of 6
r2[,32:95] <- 500
#Now I use the original raster to recode the cells in r2 which are no longer NA that were NA in r
r3 <- terra::mask(r2, r)
plot(r3)
I suspect there is a more elegant solution but I can't figure it out. Any suggestions?
terra::cellFromXY
would work for you. You can then use a cell index in the same way that you already are.