Skip to content

Instantly share code, notes, and snippets.

@obrl-soil
Last active March 5, 2017 23:02
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 obrl-soil/839b192da46978351733483421db22f8 to your computer and use it in GitHub Desktop.
Save obrl-soil/839b192da46978351733483421db22f8 to your computer and use it in GitHub Desktop.
# a simplified version of the sampler used in https://github.com/obrl-soil/disaggregation
# takes n random samples in each polygon of a spatialpolygonsdataframe
# note that n samples may not be acheived if the polygon shape is particularly convoluted
# indata = spatialpolygonsdataframe
# sample_rate = positive integer
# pid_field = character string - column name. if omitted, rownames used instead
poly_sampler <- function(indata = NULL, sample_rate = NULL, pid_field = NULL) {
crs <- indata@proj4string
sample_points <- vector('list', length = length(indata@polygons))
# sampling loop (one polygon at a time)
for (i in 1:length(indata@polygons)) {
polyid <- if (is.null(pid_field)) {
rownames(indata@data[i, ])
} else {
indata@data[i, c(pid_field)]
}
spoints <- spsample(indata[i, ], n = sample_rate, type = "random", iter = 10)
data <- data.frame("POLY_NO" = polyid,
"SAMP_NO" = 1:length(spoints),
"SAMP_X" = spoints@coords[, 1],
"SAMP_Y" = spoints@coords[, 2],
stringsAsFactors = FALSE)
spointsdf <- SpatialPointsDataFrame(spoints, data, proj4string = crs)
sample_points[[i]] <- spointsdf
}
# combine the samples from each polygon into one SPDF and return
all_samplepoints <- do.call('rbind', sample_points)
return(all_samplepoints)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment