我正在尝试将空间点数据连接到空间多边形数据。
前段时间,这个非常有用的帖子发布了: How to pick up the information for the nearest associated polygon to points using R?
我正在尝试使用OP发布的代码:
library(rgeos)
library(sp)
library(maptools)
library(rgdal)
library(sp)
ky.map <- readShapeSpatial("~/KYcounties.shp")
points.xy <- readShapeSpatial('~/points.shp') # Sample data of the points file
# is below.
我正在使用的功能是
IntersectPtWithPoly <- function(x, y) {
# Extracts values from a SpatialPolygonDataFrame with SpatialPointsDataFrame,
# and appends table (similar to ArcGIS intersect)
# Args:
# x: SpatialPoints*Frame
# y: SpatialPolygonsDataFrame
# Returns:
# SpatialPointsDataFrame with appended table of polygon attributes
# Set up overlay with new column of join IDs in x
z <- overlay(y, x)
# Bind captured data to points dataframe
x2 <- cbind(x, z)
# Make it back into a SpatialPointsDataFrame
# Account for different coordinate variable names
if(("coords.x1" %in% colnames(x2)) & ("coords.x2" %in% colnames(x2))) {
coordinates(x2) <- ~coords.x1 + coords.x2
} else if(("x" %in% colnames(x2)) & ("x" %in% colnames(x2))) {
coordinates(x2) <- ~x + y
}
# Reassign its projection if it has one
if(is.na(CRSargs(x@proj4string)) == "FALSE") {
x2@proj4string <- x@proj4string
}
return(x2)
}
并被称为
test <- IntersectPtWithPoly(points.xy, ky.map)
除非得到:
,哪个效果很好Warning message: 'overlay' is deprecated. Use 'over' instead.
以及连接多边形字段的一堆NA。
足够公平:
z <- over(y, x)
但这让我:
Error in data.frame(..., check.names = FALSE) : arguments imply differing
number of rows: 96, 121
以下是我正在使用的点数据示例(放入QGIS并导出为shapefile):
structure(list(ID = c(5L, 11L, 33L, 41L, 73L, 119L, 175L, 206L,
216L, 229L), Latitude = c(38.239829, 38.9231075, 38.04169866,
38.13953849, 38.14800534, 37.85059283, 38.17820492, 38.00833019,
38.22189947, 36.87255699), Longitude = c(-85.746211, -84.4108925,
-84.49738797, -85.6776972, -85.02502406, -84.57452618, -85.56667237,
-84.42084641, -85.48653626, -84.22021486)), .Names = c("ID",
"Latitude", "Longitude"), row.names = c(NA, 10L), class = "data.frame")
我在Google云端硬盘上分享了shapefile:https://docs.google.com/file/d/0B1bNxpx4XS8dSFJlOTlQSUw0LTg/edit?usp=sharing
思想?
答案 0 :(得分:0)
使用spatialEco
库有一个简单的解决方案。
library(spatialEco)
# intersect points in polygon
pts <- point.in.poly(pts, ply)
# check plot
plot(ply)
plot(a, add=T)
# convert to data frame, keeping your data
pts <- as.data.frame(pts)