R语言 裁剪并连接两个空间数据

nafvub8i  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(167)

我有两个数据集,第一个(df1)有纬度和经度,第二个(usa)是(sf,datafarme)。

df1 = structure(list(Latitude = c(44.11, 45.78, 44.49, 46.87, 44.81, 
44.11, 44.45, 45.78, 44.79, 45.22, 47.3, 44.24, 44.33, 44.96, 
44.98, 44.73, 44.36, 45.14, 45.98, 46.59, 46.53, 44.48, 45.09, 
44.31, 45.79, 44.74, 45.02, 44.71, 44.55, 46.91, 44.58, 44.1, 
45.39, 44.84, 45.08, 46.16, 44.49, 44.31, 44.37, 44.36, 44.38, 
46.88, 46.21, 44.31, 44.7, 44.68), Longitude = c(-70.15, -87.08, 
-73.12, -68.03, -68.8, -70.15, -71.17, -87.08, -85.64, -67.26, 
-68.57, -73.49, -71.75, -72.16, -74.82, -73.44, -74.11, -87.6, 
-86.21, -87.4, -84.33, -83.33, -83.41, -85.39, -84.71, -84.69, 
-84.66, -85.64, -87.92, -67.99, -70.54, -70.17, -68.52, -68.72, 
-69.86, -67.82, -73.2, -69.68, -69.75, -69.74, -69.79, -68.02, 
-67.79, -69.68, -67.57, -67.64)), row.names = c(NA, -46L), class = "data.frame")

第二个是"usa",类是"sf" "data.frame"

library(sf)
library(rnaturalearth)

world <- ne_countries(scale = "medium", returnclass = "sf")
usa = filter(world,admin =="United States of America")
usa <- st_as_sf(maps::map("state", fill=TRUE, plot =FALSE))

我想子集数据点停留在多边形。我已经创建了临时的SpatialPointsDataFrame来排除点"df1"可以在"usa"之外,但我有这个错误:
h中的错误(简单错误(消息,调用)):在为函数"over"选择方法时计算参数"y"时出错:as()中内部问题:"sf" is(object,"data.frame")为TRUE,但元数据Assert"is"关系为FALSE
如何裁剪这两个数据集:

vc6uscn9

vc6uscn91#

我们可以获取USAMap并将数据框转换为sf对象,如下所示:

library(sf)
library(rnaturalearth)
library(ggplot2)

usa <- ne_countries(country = 'United States of America', 
                    scale = "medium", returnclass = "sf")

pts <- st_sf(geometry = st_sfc(st_multipoint(as.matrix(df1[2:1])), 
                               crs = st_crs(usa)))

我们可以绘制一张美国大陆的Map,上面的点重叠如下:

usamap <- ggplot(usa) + geom_sf()

usamap + 
  geom_sf(data = pts) + 
  coord_sf(xlim = c(-130, -60), ylim = c(20, 50))

然后,我们可以使用st_intersection来获取与USAMap相交的点,并将它们保存为sf对象:

filtered_pts <- st_intersection(pts, usa)

当我们再次绘图时,我们会看到大部分点都保留了下来,有几个点似乎就在缅因州州海岸附近,但却被删除了:

usamap + 
  geom_sf(data = filtered_pts) + 
  coord_sf(xlim = c(-130, -60), ylim = c(20, 50))

相关问题