sf
패키지를 사용하여 동일한 결과를 얻을 수 있습니다 . 아래에서 재현 가능하고 주석이 달린 코드를 확인하십시오. 이 패키지 sf
는 공간 객체를 간단한 피처 객체로 처리하는 데 사용됩니다. 이 답변에서 패키지 raster
는 다운로드 예제 다각형 데이터와 dplyr
마지막에 데이터 변환을위한 패키지에만 사용됩니다 .
# Load libraries ----------------------------------------------------------
library(raster)
library(sf)
library(dplyr)
# Get sample data ---------------------------------------------------------
# Get polygon
polygon <- getData('GADM', country='URY', level = 1)[,1] # Download polygon of country admin level 1
polygon <- st_as_sf(polygon) # convert to sf object
colnames(polygon) <- c("id_polygons", "geometry") # change colnames
polygon$id_polygons <- paste0("poly_", LETTERS[1:19]) # change polygon ID
# Get sample random poins from polygon bbox
set.seed(4)
bbox <- st_as_sfc(st_bbox(polygon))
points <- st_sample(x = bbox, size = 100, type = "random")
points <- st_as_sf(data.frame(id_points = as.character(1:100)), points) # add points ID
# Plot data ---------------------------------------------------------------
# Plot polygon + points
plot(polygon, graticule = st_crs(4326), key.pos = 1)
plot(points, pch = 19, col = "black", add = TRUE)
# Intersection between polygon and points ---------------------------------
intersection <- st_intersection(x = polygon, y = points)
# Plot intersection
plot(polygon, graticule = st_crs(4326), key.pos = 1)
plot(intersection[1], col = "black", pch = 19, add = TRUE)
# View result
table(intersection$id_polygons) # using table
# using dplyr
int_result <- intersection %>%
group_by(id_polygons) %>%
count()
as.data.frame(int_result)[,-3]