0

I recently stumbled upon the setValues()form the raster package, but I am wondering what the use case of this function is. Is there any advantage compared to normal subsetting and indexing:

r     <- raster(ncol=10, nrow=10)

#setValues Function
r     <- setValues(r, values=1, index=10)

#Normal indexing
r[10] <- 1

Both ways yield in the same result. However the documentation states that:

While you can access the 'values' slot of the objects directly, you would do that at your own peril because when setting values, multiple slots need to be changed; which is what these functions do.

What does the author mean by peril here? And what slots remain unchanged, when I use normal subsetting and not the setValues function or is there any advantage in terms of perfomance?

maRtin
  • 6,336
  • 11
  • 43
  • 66
  • When the author warns against directly modifying the 'values' slot, they're talking about not doing something like this: `r <- raster(matrix(1:9, nc=3)); r@data@values <- 100*(1:9)`. If you monkey around like that, directly modifying the low-level data structure, you're bypassing lots of nice stuff that's done for you without your being directly aware of it. Try (for instance) running `minValue(r)` before and after that direct assignment to the `values` data slot to see what I mean. And then do `getMethod("setValues", "RasterLayer")` for a more detailed look at what `setValues` does for you. – Josh O'Brien May 10 '16 at 23:33
  • Careful also: the second and third line of code in your code block aren't actually doing the same thing at all. – Josh O'Brien May 10 '16 at 23:38

1 Answers1

1

The basic use-case for setValues is if want to assign a vector of cell values to a (perhaps empty) RasterLayer. E.g.

library(raster)
r <- raster(ncol=10, nrow=10)
r <- setValues(r, 1:100)

A more R-idiomatic variation is

values(r) <- 1:100

Indexing is typically used for a few cells

r[1:5] <- NA

But you can also use it to set values for all cells

r[] <- 1:100
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63