terra icon indicating copy to clipboard operation
terra copied to clipboard

New feature for spatSample() method = 'regular'

Open matthewseanmarcus opened this issue 3 years ago • 1 comments

It would be useful for spatSample() to be able to ignore NA's when method = 'regular'. In my case, I have a raster with many NA's throughout. I would like to sample pixels from a regular lattice, however, if the sampled pixel is an NA, I would like the function to select the nearest pixel with a value.

matthewseanmarcus avatar Nov 02 '22 15:11 matthewseanmarcus

Maybe instead of implementing a new function it would be easier to use bilinear interpolation from extract()?

library("terra")
set.seed(1)

f = system.file("ex/logo.tif", package = "terra")
r = rast(f)[[1]]
idx = sample(seq_len(ncell(r)), 3000)
r[idx] = NA

smp = spatSample(r, 100, method = "regular", as.points = TRUE)
smp2 = extract(r, smp, method = "bilinear", bind = TRUE)

df = data.frame(smp2)
sum(is.na(df[, 1])) #> 34
sum(is.na(df[, 2])) #> 2

or move the points using shift(), get the values again and then replace NA:

smp = spatSample(r, 100, method = "regular", as.points = TRUE)
smp2 = shift(smp, res(r)[1], res(r)[2])
smp2 = extract(r, smp2, bind = TRUE)
names(smp2) = c("a", "b")
sum(is.na(smp2$a)) #> 34
smp2$a = ifelse(is.na(smp2$a), smp2$b, smp2$a)
sum(is.na(smp2$a)) #> 14

kadyb avatar Nov 08 '22 23:11 kadyb