I have an area divided into polygons, and a dataset of observations which has a common field with the polygon layer.
I now would like to generate a random point for each dataset entry within the according polygon.
R was already a great help in digesting the dataset and even to produce shapefiles with summed values of the dataset, so I dare to post this here in the gis.stackexchange. It would be nice to have a solution in R, cause i have to create multiple subsets which can so easily be done there by a loop, so i do no have to filter the data manually in QGIS all the time.
Other solution are welcome as well.
Polygonlayer: 39 Polygons
Polyid
A1
O19
A13
Datalist: 1360 Data entries
Polyid, value1, value2, value3
A17, ..., ..., ...
O6, ..., ...
A3, ...
A4, ...
O6, ...
A8, ...
A17, ...
Goal: -> Having a point-shape with 1360 random points, which reside in the according polygon and have all attributes of the datalist.
Answer
See my example and answer
### Preparing the SpatialPointsDataFrame
spdf <- matrix(as.numeric(NA), nlevels(Poly$MatchID), 1)
spdf <- as.list(spdf)
### Sample the coordinate, match it with data in spdf. It create a list fore each factor of the MatchID
### sample(spsample()) fix the size of the sample
for (i in seq(Poly$MatchID))
spdf[i] <- SpatialPointsDataFrame(
sample(spsample(Poly[order(Poly$MatchID)==i,], n = 100, "stratified"),table(df$MatchID)[[i]]), ### table(df$MatchID)[[i]] is the size of the sample and match the sum of factors in df
df[df$MatchID==dimnames(table(df$MatchID))[[1]][i],], ## dimnames(table(df$MatchID))[[1]][i] ### match the value of the selected "factor" to select the rows of the data
proj4string=poly.crs,
match.ID=TRUE)
## Merging together the list to make on SpatialDataFrame
do.call("rbind", spdf) -> spdf
No comments:
Post a Comment