https://sciences.social/@mortenfrisch/115228046285688665
library(terra)
#> terra 1.8.64
xysize <- 100
nr <- 10
nc <- 20
r <- rast(ext(0, nc * xysize, 0, nr * xysize), res = xysize/2)
# ## xmin, xmax, ymin, ymax (the outer edges of the left, right, bottom, top cells)
## these are derived from our abstract description above, but this is where you start with centroids
## (they might be regular, and a complete grid, or they might be arbitrary - obvsly the abstract spec is higher fidelity)
xy <- tibble::as_tibble(xyFromCell(r, 1:ncell(r)))
## now, we have an n for every cell specified somehow
xy$n <- sample(0:20, ncell(r), replace = TRUE)
xy$id <- 1:nrow(xy)
xy$w <- xysize ## copy everything onto the list we iterate over, for parallel
library(purrr)
mirai::daemons(parallelly::availableCores())
fun <- in_parallel(function(.x) {
w <- .x$w[1]
if (.x$n < 1) return(NULL)
cbind(x = runif(.x$n, .x$x - w, .x$x + w),
y = runif(.x$n, .x$y - w, .x$y + w),
id = .x$id[1])
})
l <- map(split(xy, xy$id), fun)
mirai::daemons(0)
d <- do.call(rbind, l)
plot(r)
points(d[,"x"], d[,"y"], pch = ".")
text(xy, label = xy$n, col = "firebrick", cex = .5)
plot(as.polygons(r), add = T, border = "grey")Created on 2025-09-19 with reprex v2.0.2
