我想创建一个数据集,其中包含非相交多边形及其属性,以及两个/所有多边形相交时的属性。
为了演示这个问题,我创建了一些虚构的数据
set.seed(131)
library(sf)
#create example data
m = rbind(c(0,0), c(1,0), c(1,1), c(0,1), c(0,0))
p = st_polygon(list(m))
n = 20
l = vector("list", n)
for (i in 1:n)
l[[i]] = p + 10 * runif(2)
s = st_sfc(l)
plot(s, col = sf.colors(categorical = TRUE, alpha = .5))
title("overlapping squares")
#convert to sf object
s <- st_as_sf(s)
#add some random info
s$tree_type <- rep(c("oak", "pine", "fir"), length.out=nrow(s))
它看起来像这个x1c 0d1x
数据是这样的:
Simple feature collection with 20 features and 1 field
Geometry type: POLYGON
Dimension: XY
Bounding box: xmin: 0.3840939 ymin: 1.132567 xmax: 10.19807 ymax: 10.14945
CRS: NA
First 10 features:
x tree_type
1 POLYGON ((2.06437 1.249422,... oak
2 POLYGON ((2.932732 3.757797... pine
3 POLYGON ((8.463468 5.292048... fir
4 POLYGON ((5.186254 2.378545... oak
5 POLYGON ((3.263181 9.149452... pine
6 POLYGON ((4.162483 3.446414... fir
7 POLYGON ((8.651544 3.160404... oak
8 POLYGON ((5.231186 2.916041... pine
9 POLYGON ((0.3840939 6.87075... fir
10 POLYGON ((7.742229 4.721718... oak
然后像这样做一个自相交
s_intersection <- st_intersection(s)
它会产生这样的数据
Simple feature collection with 31 features and 3 fields
Geometry type: GEOMETRY
Dimension: XY
Bounding box: xmin: 0.3840939 ymin: 1.132567 xmax: 10.19807 ymax: 10.14945
CRS: NA
First 10 features:
tree_type n.overlaps origins x
1 oak 1 1 POLYGON ((2.06437 1.249422,...
2 pine 1 2 POLYGON ((3.932732 4.757797...
3 fir 1 3 POLYGON ((8.463468 6.292048...
4 oak 1 4 POLYGON ((6.186254 2.378545...
5 pine 1 5 POLYGON ((3.263181 9.149452...
6 fir 1 6 POLYGON ((4.162483 3.446414...
7 oak 1 7 POLYGON ((9.651544 3.160404...
4.1 oak 2 4, 8 POLYGON ((6.186254 2.916041...
8 pine 1 8 MULTIPOLYGON (((5.826989 3....
9 fir 1 9 POLYGON ((0.3840939 6.87075...
我想做的是用两个多边形的属性替换列origins
。例如,多边形4.1将变为oak, pine
。如果是两列的话就好了。我考虑解决这个问题的方法是取消列出origins
列中的观察结果,以便每个值都在自己的列中,然后将多边形的属性绑定到多个origins
列中的每个值。但有没有更简单的方法呢?
2条答案
按热度按时间wh6knrhe1#
使用自相交的方法是正确的,但需要将原始几何体与其自身完全相交,因此可以使用
st_intersects
进行连接来完成此操作。3duebb1j2#
一种可能性,为了方便使用{dplyr}:
编辑多个属性列的广义解:
或者,如果您想将多边形复制到每种树类型的一行中,则从{tidyr}中提取
separate_rows
可能很方便。