r - Random number inside regular polygon -


i need generate n points inside of n-gon distributed uniformly. additionally, want store in matrix nx2.

you can use spsample in sp package:

library(sp)  pol <- matrix(c(0 ,0 ,2 ,0 ,2 ,2 ,0 , 2, 0, 0), byrow = t, ncol = 2) pol <- polygon(pol) spsample(pol, 100, type = "random") 

example:

pol <- matrix(c(5 ,1.5 ,1 ,8 ,3 ,12 ,8 , 10, 14, 5), byrow = t, ncol = 2) pol <- polygon(pol) s <- spsample(pol, 1000, type = "random") pol@coords %>% as.data.frame() %>% set_names(c("x", "y")) %>%   ggplot(aes(x, y)) + geom_polygon(color = "black") +    geom_point(data = s@coords %>% data.frame() %>% set_names(c("x", "y")), colour = "white") 

enter image description here


Comments