在 R 中迭代 SpatialPoints 和 SpatialPolygonsDataFrame 合并

iterate SpatialPoints and SpatialPolygonsDataFrame merge in R

我正在尝试遍历创建 SpatialPolygonsDataFrames 列表的质心的过程(每个列表中都有几个多边形特征),结果 SpatialPoints 保留了 SpatialPoints 的属性(数据)父多边形。我试过 sp::over 函数,但它似乎有问题,因为质心不一定与父多边形重叠。此外,我是 coding/R 的新手,不知道如何使用 apply 函数在 for 循环 and/or 中实现此目的。

所以具体来说,我需要 (1) 找到一个不同的函数,它将 link 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

我发现 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/