2

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?

1
  • Depending on coordinate precision, I would imagine that terra::cellFromXY would work for you. You can then use a cell index in the same way that you already are. Commented Feb 1, 2023 at 23:19

2 Answers 2

4

You could first create a longitude raster with init, mask that with your data and then use mask again, or ifel

library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
lon <- init(r, "x") |> mask(r)

x <- ifel(lon > 6, 500, r)
# or 
y <- mask(r, lon>6, maskvalue=TRUE, updatevalue=500)
2
  • That is slick, glad you added this. It is quite similar to a method that Workstation arc/info use to have. So, you can use init for creating row, column and cell number rasters as well? Commented Feb 2, 2023 at 5:12
  • 1
    That is correct about init . (And about $$COLMAP and con 😉) Commented Feb 2, 2023 at 5:30
2

Well, not memory safe but, you do not need to create unnecessary objects.

Read data

library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
  plot(r)

Create coordinate vectors that are ordered the same as the cells in the raster and then pass it to which to pull the cell indices associated with a query of the vector. The index xyFromCell(r, 1:ncell(r))[,1] is in reference to the first coordinate column (long) so, for lat it would be xyFromCell(r, 1:ncell(r))[,2]. The which function supports multiple criteria query using | or & and so, querying both coordinates can be done in one fell swoope.

r2 <- r #make copy 
  r2[which(xyFromCell(r, 1:ncell(r))[,1] > 6)] <- 500
    plot(mask(r2,r))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.