正多边形内的随机数

时间:2016-08-09 00:47:58

标签: r

我需要在均匀分布的n-gon内生成n个点。另外,我想存储在矩阵nx2中。

1 个答案:

答案 0 :(得分:3)

您可以在spsample包中使用sp

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")

示例:

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