要在数据包含多个多边形的情况下完成Spacedman的出色回答,请使用dplyr
以下代码:
library(dplyr)
library(ggplot2)
library(sp)
## use data from ggplot2:::geom_polygon example:
positions <- data.frame(id = rep(factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3")), each = 4),
x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)) %>% as.tbl
df_to_spp <- positions %>%
group_by(id) %>%
do(poly=select(., x, y) %>%Polygon()) %>%
rowwise() %>%
do(polys=Polygons(list(.$poly),.$id)) %>%
{SpatialPolygons(.$polys)}
## plot it
plot(df_to_spp)
只是为了好玩,您可以与ggplot2
使用初始数据帧获得的图进行比较:
ggplot(positions) +
geom_polygon(aes(x=x, y=y, group=id), colour="black", fill=NA)
请注意,上面的代码假定每个id仅包含一个polyogn。如果某些ID具有不相交的多边形,我想应该在数据集中添加另一列,首先group_by
是子ID,然后使用group_by(upper-id)
代替rowwise
使用该purrr::map
功能的相同代码:
df_to_spp <- positions %>%
nest(-id) %>%
mutate(Poly=purrr::map(data, ~select(., x, y) %>% Polygon()),
polys=map2(Poly, id, ~Polygons(list(.x),.y))) %>%
{SpatialPolygons(.$polys)}