3

I have:

  • raster_1: an integer raster with non-sequential values i (101, 130, 240, 323)
  • i: a watershed discharging X of sediment in the environment
  • raster_2: represents the water quality for each watershed i with values ranging from 0 to 100,000 - named plume_i

I have ~400 rasters representing the water quality of 400 watersheds.

I would like to build a loop to set the values in raster_1 to NA for each zone (defined by the values: 101, 130, 240, 323 in raster_1) when raster_2 for the corresponding value (e.g., plume_101) is 0, using R.

For instance,

  • When raster_1 = 101 & plume_101 = 0, assign NA to raster_1 otherwise return raster_1 values
  • When raster_1 = 130 & plume 130 = 0, assign NA to raster_1 otherwise return raster_1 values
  • When raster_1 = 240 & plume 240 = 0, assign NA to raster_1 otherwise return raster_1 values and so forth...

How can I do this?

2
  • plume_101 should only have values where raster_1 is 101?
    – Elio Diaz
    Commented Jan 16, 2021 at 3:35
  • 1
    @ElioDiaz yes you are correct and thank you for your answer it was super helpful and i was able to get it work!!
    – Jade
    Commented Jan 20, 2021 at 23:39

1 Answer 1

3

If I understood, you will be overwriting raster_1, putting NA when the condition is met. Here, the key is get which fetches an object from the environment by a string name.

library(raster)

# we create some rasters with same extent
m = matrix(sample(c(101,130,240,323),100, replace = T), ncol = 10)
r = raster(m)
p_101 = matrix(sample(0:10, 100, replace = T), ncol = 10)
plume_101 = raster(p_101)
p_130 = matrix(sample(0:10, 100, replace = T), ncol = 10)
plume_130 = raster(p_130)
p_240 = matrix(sample(0:10, 100, replace = T), ncol = 10)
plume_240 = raster(p_240)
p_323 = matrix(sample(0:10, 100, replace = T), ncol = 10)
plume_323 = raster(p_323)


par(mfrow = c(2,2))
for(i in c(101,130,240,323)) {
  r[r[] == i & get(sprintf("plume_%s", i))[] == 0] = NA
  plot(r, main = i, col = c("gold", "blue","brown", "tomato", "green"))
}

In the plot you may see how subsequently NA are added in each iteration enter image description here

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.