공간 점 데이터를 R의 다각형에 결합

점 데이터와 다각형 데이터 사이의 공간 결합을 수행하려고합니다.

csv 파일 A에 이벤트의 공간 좌표를 나타내는 데이터가 있고 영역의 경계를 다각형으로 포함하는 shapefile B라는 다른 파일이 있습니다.

head(A)
  month   longitude latitude lsoa_code                   crime_type
1 2014-09 -1.550626 53.59740 E01007359        Anti-social behaviour
2 2014-09 -1.550626 53.59740 E01007359                 Public order
3 2014-09 -1.865236 53.93678 E01010646        Anti-social behaviour

head(B@data)
  code      name                                  altname
0 E05004934 Longfield, New Barn and Southfleet    <NA>
1 E05000448                   Lewisham Central    <NA>
2 E05003149                            Hawcoat    <NA>

내 영역 A에서 발생하는 범죄 이벤트를 맵핑하기 위해 범죄 데이터 A를 모양 파일 B에 결합하려고합니다. 불행히도 codeA의 코드가 B의 코드와 다른 단위를 참조하므로 속성 결합을 수행 할 수 없습니다 .

많은 튜토리얼과 게시물을 읽었지만 답변을 찾을 수 없습니다. 나는 시도했다 :

joined = over(A, B)

그리고 overlay,하지만 내가 원하는 것을 달성하지 않았다.

이 결합을 직접 수행하는 방법이 있습니까? 아니면 A에서 다른 형식으로 중간 변환이 필요합니까?

개념적으로 나는 codeB 의 영역에 속하는 A의 지점을 선택하고 싶습니다 ( “ArcGIS의 공간 위치에 기초하여”와 유사 함).

누군가이 문제가 있고 해결 했습니까?



답변

spaceEco 패키지의 point.in.poly 함수는 sp 다각형 객체와 교차하는 점의 SpatialPointsDataFrame 객체를 반환하고 선택적으로 다각형 속성을 추가합니다.

먼저 require 패키지를 추가하고 예제 데이터를 만듭니다.

require(spatialEco)
require(sp)
data(meuse)
coordinates(meuse) = ~x+y
sr1=Polygons(list(Polygon(cbind(c(180114, 180553, 181127, 181477, 181294, 181007, 180409,
  180162, 180114), c(332349, 332057, 332342, 333250, 333558, 333676,
  332618, 332413, 332349)))),'1')
sr2=Polygons(list(Polygon(cbind(c(180042, 180545, 180553, 180314, 179955, 179142, 179437,
  179524, 179979, 180042), c(332373, 332026, 331426, 330889, 330683,
  331133, 331623, 332152, 332357, 332373)))),'2')
sr3=Polygons(list(Polygon(cbind(c(179110, 179907, 180433, 180712, 180752, 180329, 179875,
  179668, 179572, 179269, 178879, 178600, 178544, 179046, 179110),
  c(331086, 330620, 330494, 330265, 330075, 330233, 330336, 330004,
  329783, 329665, 329720, 329933, 330478, 331062, 331086)))),'3')
sr4=Polygons(list(Polygon(cbind(c(180304, 180403,179632,179420,180304),
  c(332791, 333204, 333635, 333058, 332791)))),'4')
sr=SpatialPolygons(list(sr1,sr2,sr3,sr4))
srdf=SpatialPolygonsDataFrame(sr, data.frame(row.names=c('1','2','3','4'), PIDS=1:4, y=runif(4)))

이제 데이터를 빠르게보고 플로팅합니다.

head(srdf@data)  # polygons
head(meuse@data) # points
plot(srdf)
points(meuse, pch=20)

마지막으로 다각형과 점을 교차시킬 수 있습니다. 결과는 srdf 다각형 데이터에 포함 된 두 개의 추가 속성 (PIDS, y)이있는 SpatialPointsDataFrame 객체입니다.

  pts.poly <- point.in.poly(meuse, srdf)
    head(pts.poly@data)

다각형 데이터에 고유 식별 열이 없으면 쉽게 추가 할 수 있습니다.

srdf@data$poly.ids <- 1:nrow(srdf) 

점과 다각형이 교차되면 다각형 데이터의 속성 인 고유 다각형 ID를 사용하여 점을 집계 할 수 있습니다.

# Number of points in each polygon
tapply(pts.poly@data$lead, pts.poly@data$PIDS, FUN=length)

# Mean lead in each polygon
tapply(pts.poly@data$lead, pts.poly@data$PIDS, FUN=mean)


답변

over()패키지 sp에서 약간 혼란 스러울 수 있지만 잘 작동합니다. 나는 이미 coordinates(A) <- ~longitude+latitude다음 과 같이 “A”를 공간적으로 만들었다 고 가정합니다 .

# Overlay points and extract just the code column: 
a.data <- over(A, B[,"code"])

점 공간 객체 대신 동일한 no를 가진 데이터 프레임을 제공합니다. 행을 A로, B에서 교차하는 각 다각형의 단일 변수 “코드”입니다.

# Add that data back to A:
A$bcode <- a.data$code


답변

다음은 dplyr과 같은 솔루션입니다.

library(spdplyr)

ukcounties <- geojsonio::geojson_read("data/Westminster_Parliamentary_Constituencies_December_2018_UK_BGC/uk_country.geojson",
                                      what = "sp")
pop <- read_excel("data/SAPE20DT7-mid-2017-parlicon-syoa-estimates-unformatted.xls",sheet = "data")
pop <- janitor::clean_names(pop)

ukcounties_pop <- ukcounties %>% inner_join(pop, by = c("pcon18nm" = "pcon11nm"))

인구 데이터는 https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates/datasets/parliamentaryconstituencymidyearpopulationestimates 에서 제공됩니다.

https://geoportal.statistics.gov.uk/datasets/westminster-parliamentary-constituencies-december-2018-uk-bgc/data?page=1 에서 다운로드 한 쉐이프 파일을 geoJson으로 변환해야했습니다.

당신은 그렇게 할 수 있습니다 :

uk_constituencies <- readOGR("data/Westminster_Parliamentary_Constituencies_December_2018_UK_BGC/Westminster_Parliamentary_Constituencies_December_2018_UK_BGC.shp")
uk_constituencies # this is in tmerc format. we need to convert it to WGS84 required by geoJson format.

# First Convert to Longitude / Latitude with WGS84 Coordinate System
wgs84 = '+proj=longlat +datum=WGS84'
uk_constituencies_trans <- spTransform(uk_constituencies, CRS(wgs84))

# Convert from Spatial Dataframe to GeoJSON
uk_constituencies_json <- geojson_json(uk_constituencies_trans)

# Save as GeoJSON file on the file system.
geojson_write(uk_constituencies_json, file = "data/Westminster_Parliamentary_Constituencies_December_2018_UK_BGC/uk_country.geojson")

#read back in:
ukcounties <- geojsonio::geojson_read("data/Westminster_Parliamentary_Constituencies_December_2018_UK_BGC/uk_country.geojson",
                                      what = "sp")


답변