当前位置: 动力学知识库 > 问答 > 编程问答 >

How to merge spatial datasets of coordinates using R?

问题描述:

I have two separate spatial point data frames in R (colored red and black in the attached plot). How to import data attributes from the 'red' dataset into the nearest location in the 'black' dataset in R?

网友答案:

Here is one way to approach the problem.

library(raster)
library(sp)

### create some example datasets
coords_A = cbind(runif(10, 1, 10), runif(10,1,10))
sp_A = SpatialPoints(coords_A)
spdf_A = SpatialPointsDataFrame(coords_A, data.frame(varA=letters[1:10]))

coords_B = cbind(runif(10, 1, 10), runif(10,1,10))
sp_B = SpatialPoints(coords_B)
spdf_B = SpatialPointsDataFrame(coords_B, data.frame(varB=letters[11:20], varC=LETTERS[11:20]))

### compute the complete distance matrix between the two sets of points
dist_mat <- pointDistance(spdf_A, spdf_B, lonlat = FALSE, allpairs = TRUE)

### identify nearest point in dataset B for every point in dataset A
nearest <- apply(dist_mat, 1, which.min)

### bind together the data from the dataset B (in your case the "red points")
### at the closest point to dataset A ("black points")
[email protected]<- cbind([email protected], [email protected][nearest,])
分享给朋友:
您可能感兴趣的文章:
随机阅读: