Home > front end >  Sample points at random location within cells that are not NA with terra spatSample
Sample points at random location within cells that are not NA with terra spatSample

Time:10-18

I have a SpatRaster with values of 1 and NA. I would like to generate random points only within cells that are 1.

The only way I can think of doing this is with method = "stratified" which only add points to non-NA areas. However this does not generate points at random within a cell, instead placing points at the cell centre. How can I generate points at random locations within non-NA cells?

library(terra)
rr <- rast(ncol=10, nrow=10)
set.seed(1)
values(rr) <- round(runif(ncell(rr), 0, 1))
rr <- classify(rr, cbind(0, NA))
s <- spatSample(rr,
           size = 10,
           method = "stratified",
           as.points = T)

CodePudding user response:

I suppose you can add some "noise" like I do below

library(terra)
rr <- rast(ncol=10, nrow=10)
set.seed(1)
n <- 10
values(rr) <- round(runif(ncell(rr), 0, 1))
rr <- classify(rr, cbind(0, NA))
s <- spatSample(rr, size = n,
           method = "stratified", xy=TRUE)

x_noise <- runif(n, -xres(rr), xres(rr)) / 2 
y_noise <- runif(n, -yres(rr), yres(rr)) / 2

s[,1:2] <- s[,1:2]   cbind(x_noise, y_noise)

plot(rr)
points(s[,1:2])

Since all cells that are not of interest are NA, you do not need to use method="stratified", and you can instead do

s <- spatSample(rr, n, na.rm=TRUE, xy=TRUE) 
  • Related