2016-12-25 84 views
2

我在R中有两个单独的空间点数据帧(附图中的红色和黑色)。如何将数据属性从“红色”数据集导入R中“黑色”数据集中最近的位置?如何使用R合并坐标空间数据集?

plot

+0

这是一个关于空间数据集的普通R编程问题 - 答案在我看来非常好 - 应该发布给大家来欣赏。我无法在任何其他论坛找到这个问题的答案。 –

回答

2

下面是解决这个问题的方法之一。

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,]) 
+0

你的模拟例子像一个魅力工作,谢谢! –