簡體   English   中英

R 中數據幀的空間子集

[英]Spatial subset of data frame in R

我有一個使用plot()繪制的大數據框。 然后我用:

library(splancs) 

polygon_xy = getpoly(quiet=FALSE) 

並在 plot 到 select 我感興趣的區域上畫了點。 這生成了我繪制的多邊形的 x,y 坐標。

我想提取位於多邊形內的數據,或者將我的 df 子集化以僅包含位於多邊形內的點。 任何建議如何做到這一點?

當您使用plot並讓getpoly識別坐標時,點數據需要采用特定格式(即帶有 x 和 y 的矩陣)。

library(splancs)
library(tidyverse)
library(sf)

set.seed(543)
xy <-
  cbind(x = runif(n = 25, min = -118, max = -117),
        y = runif(n = 25, min = 40, max = 42))

plot(xy)

# Draw a polygon for study area.
poly <- getpoly()

# Convert to sf objects.
polysf <- st_as_sf(as.data.frame(poly), coords = c("V1", "V2"), crs = 4326) %>% 
  dplyr::summarise() %>%
  st_cast("POLYGON") %>% 
  st_convex_hull()

xysf <- st_as_sf(as.data.frame(xy), coords = c("x", "y"), crs = 4326)

# Do an intersection to keep only points inside the drawn polygon.
xy_intersect <- st_intersection(polysf, xysf)

Output

Simple feature collection with 9 features and 0 fields
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: -117.7913 ymin: 40.82405 xmax: -117.4264 ymax: 41.7448
Geodetic CRS:  WGS 84
                    geometry
1 POINT (-117.4264 41.18712)
2  POINT (-117.5756 41.7448)
3 POINT (-117.7913 40.82405)
4 POINT (-117.7032 41.15077)
5 POINT (-117.5634 41.23936)
6 POINT (-117.7441 40.84163)
7  POINT (-117.692 41.27514)
8 POINT (-117.6864 40.98462)
9 POINT (-117.5759 40.88477)

library(mapview)中的mapview::mapview(xy_intersect)繪制

在此處輸入圖像描述

但是,如果您想從原始 dataframe 中提取行,那么這里有另一個技巧,用於提取落在繪制多邊形內的點(例如,當多邊形坐標看起來像 0.003456 時)。

library(splancs)
library(tidyverse)

set.seed(543)
xy <-
  cbind(x = runif(n = 25, min = -118, max = -117),
        y = runif(n = 25, min = 40, max = 42))

plot(xy)

# Draw a polygon for study area.
poly <- getpoly()

# Plot the results.
plot(xy)
polygon(poly)

# This will return a logical vector for points in the polygon
io <- inout(xy, poly)
points(xy[io,], pch = 16, col = "blue")

# Then, can use the index from io to extract the points that 
# are inside the polygon from the original set of points.
extract_points <- as.data.frame(xy)[which(io == TRUE),]

extract_points

Output

           x        y
2  -117.4506 41.17794
3  -117.4829 40.71030
8  -117.4679 40.71702
19 -117.3354 40.53687
21 -117.5219 40.47077
22 -117.4876 40.18188
25 -117.2015 40.86243

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM