Skip to content

Instantly share code, notes, and snippets.

@pierreroudier
Created January 28, 2022 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pierreroudier/7d1e8926ff8908d2e3fc937c81cf1e01 to your computer and use it in GitHub Desktop.
Save pierreroudier/7d1e8926ff8908d2e3fc937c81cf1e01 to your computer and use it in GitHub Desktop.
Sample raster
library(sp)
library(raster)
library(ggplot2)
# load example data
data("meuse.grid", package = "sp")
coordinates(meuse.grid) = ~x+y
proj4string(meuse.grid) <- CRS("+init=epsg:28992")
gridded(meuse.grid) = TRUE
# convert to raster
r <- raster(meuse.grid[, 'dist'])
# downscale resolution
r <- aggregate(r, fact = 4)
# convert raster to data.frame
df <- as.data.frame(r, xy = TRUE, na.rm = TRUE)
# run sampling
idx <- sample(
1:nrow(df),
size = 30,
prob = df$dist,
replace = TRUE
)
# extract random coords within cells
coords <- do.call(
rbind,
lapply(
idx,
function(i) {
centre_x <- df$x[i]
centre_y <- df$y[i]
x <- centre_x + res(r) * (runif(1) - 0.5)
y <- centre_y + res(r) * (runif(1) - 0.5)
data.frame(x = x, y = y)
}
)
)
ggplot() +
geom_raster(data = df, aes(x = x, y = y, fill = dist)) +
scale_fill_viridis_c() +
geom_point(data = coords, aes(x = x, y = y), shape = 23, fill = "red") +
coord_equal() +
theme_minimal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment