我正在尝试遍历创建SpatialPolygonsDataFrames
列表(每个都有多个多边形要素)的质心的过程,结果SpatialPoints
保留父多边形的属性(数据) 。我已经尝试过sp::over
函数,但是它似乎有问题,因为质心不一定与父多边形重叠。此外,我是编码/ R的新手,不知道如何在for
循环中和/或使用apply
函数来实现这一点。
因此,具体地说,我需要(1)找到将SpatialPolygonsDataFrames
与关联的SpatialPoints
(质心)链接起来的其他函数; (2)遍历整个过程并将SpatialPolygonsDataFrames
数据与适当的SpatialPoints
合并-我不知道在运行循环时如何将一个列表的索引值与另一个列表的索引值进行匹配
这是单个SpatialPolygonsDataFrames
对象的可重现示例,显示使用sp::over
无效,因为某些质心最终不会重叠父多边形:
library(maptools) ## For wrld_simpl
library(sp)
## Example SpatialPolygonsDataFrames (SPDF)
data(wrld_simpl) #polygon of world countries
spdf1 <- wrld_simpl[1:25,] #country subset 1
spdf2 <- wrld_simpl[26:36,] #subset 2
spdf3 <- wrld_simpl[36:50,] #subset 3
spdfl[[1]]@data
#plot, so you can see it
plot(spdf1)
plot(spdf2, add=TRUE, col=4)
plot(spdf3, add=TRUE, col=3)
#make list of SPDF objects
spdfl<-list()
spdfl[[1]]<-spdf1
spdfl[[2]]<-spdf2
spdfl[[2]]<-spdf3
#create polygon centroids for each polygon feature (country) within spdfl[[1]]
spdf1c <- gCentroid(spdfl[[1]], byid=TRUE)
plot(spdfl[[1]])
plot(spdf1c, add=TRUE)
#add attributes 'NAME' and 'AREA' to SpatialPoints (centroid) object from SPDF data
spdf.NAME <- over(spdf1c, spdfl[[1]][,"NAME"])
spdf.AREA <- over(spdf1c, spdfl[[1]][,"AREA"])
spdf1c$NAME <- spdf.NAME
spdf1c$AREA <- spdf.AREA
spdf1c@data
#`sp::over` output error = name and area for ATG, ASM, BHS, and SLB are missing
答案 0 :(得分:1)
我发现SF
是用于处理R中空间数据的好软件包。我已经修复了一些错字并在下面添加了for循环的权利。
library(maptools) ## For wrld_simpl
library(sp)
library(sf)
## Example SpatialPolygonsDataFrames (SPDF)
data(wrld_simpl) #polygon of world countries
spdf1 <- wrld_simpl[1:25,] #country subset 1
spdf2 <- wrld_simpl[26:36,] #subset 2
spdf3 <- wrld_simpl[36:50,] #subset 3
spdfl[[1]]@data
#plot, so you can see it
plot(spdf1)
plot(spdf2, add=TRUE, col=4)
plot(spdf3, add=TRUE, col=3)
#make list of SPDF objects
spdfl<-list()
spdfl[[1]]<-spdf1
spdfl[[2]]<-spdf2
spdfl[[3]]<-spdf3
# Empty List for Centroids
centres <-list()
# For Loop
for (i in 1:length(spdfl)) {
centres[[i]] <- spdfl[[i]] %>%
sf::st_as_sf() %>% # translate to SF object
sf::st_centroid() %>% # get centroids
as(.,'Spatial') # If you want to keep as SF objects remove this line
}
#Plot your Spatial Objects
plot(spdfl[[1]])
plot(centres[[1]], add=TRUE)
这是使用SF和sp的解决方案。 SF非常好,因为它将内容保存为易于处理的数据帧。这里的更多信息:https://r-spatial.github.io/sf/