Last active
March 5, 2017 23:02
-
-
Save obrl-soil/839b192da46978351733483421db22f8 to your computer and use it in GitHub Desktop.
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
# 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