2
votes

I would like to get non-NA values extracted from random coordinates of a raster within each grid cell.

An example of a raster

library(raster)
r <- raster(ncol = 10, nrow = 10, xmx = -80, xmn = -150, ymn = 20, ymx = 60)
values(r) <- runif(ncell(r))

An example of a grid

grid <- raster(extent(r))
res(grid) <- 15
proj4string(grid)<- proj4string(r)
gridpolygon <- rasterToPolygons(grid)

plot(r)
plot(gridpolygon, add = T)

How can I extract a value with random coordinates for each raster portions inside each grid cells?

I am really new at this kind of stuff so any suggestions will be very welcome. Thanks.

1

1 Answers

1
votes

You didn't specify all the condition for sampling, so I'm going by some assumptions here. One can sample a point per grid polygon and extract the value. Here's how you can do it in one go and hope for the best:

# pick random points per each grid  cell and plot
set.seed(357)
pickpts <- sapply(gridpolygon@polygons, spsample, n = 1, type = "random")
sapply(pickpts, plot, add = TRUE)

# extract values of raster cells at specified points
sapply(pickpts, FUN = extract, x = r)

enter image description here

Or you can do it in a loop and sample until you get a non-NA value.

N <- length(gridpolygon@polygons)
result <- rep(NA, times = N)

for (i in 1:N) {
  message(sprintf("Trying polygon %d", i))

  pl <- gridpolygon@polygons[[i]]
  candval <- result[i] # start with NA

  # sample until you get a non-NA hit
  while (is.na(candval)) {
    pickpoint <- spsample(pl, n = 1, type = "random")
    candval <- extract(x = r, y = pickpoint)
  }

  result[i] <- candval

}
result

 [1] 0.4235214 0.6081435 0.9126583 0.1710365 0.7788590 0.9413206 0.8589753
 [8] 0.0376722 0.9662231 0.1421353 0.0804440 0.1969363 0.1519467 0.1398272
[15] 0.4783207