0

I have a raster with 2332800 cells. Half of these cells are probably oceans and unneeded. I need to update these cells with new values. Right now I'm using a for loop and it takes a very long time:

Example:

r <- raster(ncol=10, nrow=10)
values(r) <- 1:ncell(r)
df<-data.frame(ID = 1:100, values = runif(100))


for (i in 1:ncell(r)) {
  ifelse(i %in% df$ID,
         r[i]<-df$values[df$ID == i],
         NA
  )
}

With millions of cells this for loop is slow. I was thinking about using parallel processing but at the same time there might be something faster?

I also am stuck with the dataframe and cell_id query style unfortunately.

Perhaps someone has a workaround before I start playing around with the parallels and foreach package.

4
  • 2
    Please don't SHOUT. ALL-CAPS in titles are difficult to read. Instead of attracting positive attention, they are more likely to attract downvotes and look-away.
    – Vince
    Sep 30, 2022 at 22:30
  • Please edit your question to include a single, focused question.
    – Aaron
    Sep 30, 2022 at 23:21
  • 1
    @Vince I've edited the title to lower case. If you've got edit privs its better to do that than just complain in a comment. I should have done this when I first saw this Q yesterday, but I was busy answering it.
    – Spacedman
    Oct 1, 2022 at 9:38
  • I would reccomend using the terra library. Then you have a native 'terra::ifel' function negating the need for a loop. Oct 1, 2022 at 17:28

1 Answer 1

3

The one-liner would be:

r[] = df$values[match(r[], df$ID)]

This uses match to look up the df$values entry for each r[] value matching the df$ID.

Note that r[] is pretty much the same as values(r).

This might struggle if you raster is too large to hold in RAM, but 2.3M isn't so big for that. Runs in a blink of an eye on a 2000x1000 raster on my laptop.

Check on a small example first.

1
  • Sorry for the late reply. This works great! Switched over to terra as well and it's a lot faster. Thank you for your time!
    – Leo Ohyama
    Oct 10, 2022 at 19:49

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.