Geographic Information Systems Asked by karpfen on January 28, 2021
I have a RasterStack
object and want to replace some values at a set of indices in all layers. That doesn’t work as expected, however. setValues
replaces all values even though I pass a set of indices. The following code illustrates my problem:
library (raster)
# Create sample object
r1 <- raster (nrows = 10, ncols = 10)
r2 <- raster (nrows = 10, ncols = 10)
r3 <- raster (nrows = 10, ncols = 10)
values (r1) <- runif (ncell (r1))
values (r2) <- runif (ncell (r2))
values (r3) <- runif (ncell (r3))
rst <- stack (r1, r2, r3)
# Pixel IDs to replace
indexvalues <- c (1, 2, 99)
# Values to substitute
newvalues <- c (10, -10, NA)
result <- setValues (rst, newvalues, index = indexvalues)
# All values are replaced, not just the ones at the indices
plot (result)
### This is what I would expect
values (r1) [indexvalues] <- newvalues
values (r2) [indexvalues] <- newvalues
values (r3) [indexvalues] <- newvalues
rst <- stack (r1, r2, r3)
plot (rst)
Any ideas how I can get setValues
to produce my expected result or is there something else wrong? Thanks!
The values
of a stack is a matrix, so you can directly replace rows to change all the pixels in a location in a stack without having to do each layer separately:
Test stack, using fixed values per layer to make it easier to see the changes than random numbers:
> r1 = raster(matrix(50,10,10))
> r2 = raster(matrix(60,10,10))
> r3 = raster(matrix(70,10,10))
>
> rst <- stack (r1, r2, r3)
>
> plot(rst)
Then replace values by row:
> values(rst)[indexvalues,] = newvalues
>
> plot(rst)
Correct answer by Spacedman on January 28, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP