我有新西兰鸟类观测的经度和纬度,存储在Count.df、 变量下count、longitude、 和latitude。然而,其中一些出现在近海/海洋中(这是一个公民科学数据集)。
我想根据这些点是否超出 中给出的信息来对这些点进行子集化maps::map("nz"),原因有二:
如何Count.df根据它们是否落在由 划定的组(1:3)之内/之外创建一个新变量,该变量map("nz")保存为“nzmap.dat”?
谢谢,请尽量保持编码术语简单。
的子集Count.df,我有超过 17000 个观察值,这里有 10 个。请注意“计数”的值对这个问题没有意义。
df <- readr::read_table2(
"count longitude latitude
3 174.7889 -41.24632
1 174.7764 -41.25923
4 176.8865 -39.67894
1 174.7656 -36.38182
2 175.5458 -37.13479
2 175.5458 -37.13479
1 176.8862 -39.67853
1 170.6101 -45.84626
5 174.9162 -41.25709
2 176.8506 -39.51831"
)
Run Code Online (Sandbox Code Playgroud)
不幸的是,使用maps数据对点进行空间过滤是相当困难的,因为数据实际上是用于绘图而不是用于进行空间操作。幸运的是,使用该sf包来完成这种空间工作相当容易。
rnaturalearth包裹中获得了新西兰边界,这是一个方便的国家边界来源。我做了一些转换以仅保留 shapefile 中最大的三个多边形,否则我们将绘制许多可能与此地图无关的遥远岛屿。tibble只是一列经度和一列纬度。我们将其转换为点几何图形st_as_sf并绘制它,以显示它的外观。st_within来检查每个点是否在nz边界内。st_within为每个点返回该点所在的多边形索引列表,因此我们可以使用它lengths来获得我们想要的结果。这里任何0不在边界内的东西和任何在边界内的东西1。使用此新on_land属性绘图显示离岸点已适当着色。library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3
library(rnaturalearth)
nz <- ne_countries(country = "New Zealand", returnclass = "sf", scale = "large") %>%
st_cast("POLYGON") %>%
mutate(area = st_area(geometry)) %>%
top_n(3, area)
#> Warning in st_cast.sf(., "POLYGON"): repeating attributes for all sub-
#> geometries for which they may not be constant
points <- tibble(
x = runif(1000, st_bbox(nz)[1], st_bbox(nz)[3]),
y = runif(1000, st_bbox(nz)[2], st_bbox(nz)[4])
)
points
#> # A tibble: 1,000 x 2
#> x y
#> <dbl> <dbl>
#> 1 167. -44.5
#> 2 175. -40.9
#> 3 177. -43.8
#> 4 167. -44.8
#> 5 173. -39.3
#> 6 173. -42.1
#> 7 176. -41.9
#> 8 171. -44.9
#> 9 173. -41.2
#> 10 174. -39.5
#> # ... with 990 more rows
points <- st_as_sf(points, coords = c("x", "y"), crs = 4326)
plot(nz$geometry, col = "red")
plot(points, pch = 19, cex = 1, add = TRUE)
Run Code Online (Sandbox Code Playgroud)

points <- points %>% mutate(on_land = lengths(st_within(points, nz)))
#> although coordinates are longitude/latitude, st_within assumes that they are planar
plot(nz$geometry, col = "red")
plot(points, pch = 19, cex = 1, add = TRUE)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.0)于 2018 年 5 月 2 日创建。