Created
January 28, 2022 03:19
-
-
Save pierreroudier/7d1e8926ff8908d2e3fc937c81cf1e01 to your computer and use it in GitHub Desktop.
Sample raster
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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