【发布时间】:2016-08-30 16:49:12
【问题描述】:
我正在尝试合并两个包含 GPS 坐标的数据集,这样我就剩下一个数据集,其中包含来自两个数据集的变量。我正在尝试使用一个函数来实现这一点。问题是来自两个数据集的 GPS 坐标并不完全匹配。因此,任务是通过找到最接近的 gps 坐标对,将一个数据集的变量与另一个数据集的变量进行匹配。
我已经成功使用了模糊连接包,但只能获得部分匹配 (~75%)。通过下面的功能,我希望获得更高的匹配度。一个数据集比另一个短,所以这里的想法是使用两个 for 循环,每个 for 循环遍历每个数据集。
建立一个“锚点”(两个数据集的第一次观察之间的距离),这样如果两个点之间的距离小于锚点,则新的(更短的)距离成为新的锚点。 for 循环继续进行,直到找到最短距离,并将两个数据集的变量附加到新数据集的末尾,此处称为pairedData。只要使用从两个数据集中获取的最短数据集(6314 行),我就应该留下一个数据集。
我认为这个函数应该可以工作,但是 rbind() 非常慢,而且我在实现 rbindlist() 时遇到了麻烦。关于如何实现这一目标的任何想法?
combineGPS <- function(harvest,planting) {
require(sp)
require(data.table)
longH <- harvest$long
latH <- harvest$lat
longP <- planting$long
latP <- planting$lat
rowsH <- nrow(harvest)
rowsP <- nrow(planting)
harvestCoords <- cbind(longH,latH)
harvestPoints <- SpatialPoints(harvestCoords)
plantingCoords <- cbind(longP,latP)
plantingPoints <- SpatialPoints(plantingCoords)
#种植数据比收获数据短
#需要取每一行种植数据(6314),找到最近的收获数据点(16626),然后附上
anchor <- spDistsN1(plantingPoints[1,],harvestPoints[1,],longlat=FALSE)
pairedData <- data.frame(long=numeric(),
lat=numeric(),
variety=factor(),
seedling_rate=numeric(),
seed_spacing=numeric(),
speed=numeric(),
yield=numeric(),
stringsAsFactors=FALSE)
for (p in 1:rowsP){
for (h in 1:rowsH){
if(spDistsN1(plantingPoints[p,],harvestPoints[h,],longlat=FALSE) <= anchor){
anchor <- spDistsN1(plantingPoints[p,],harvestPoints[h,],longlat=FALSE)
pairedData[p,]<-c(planting[p,]$long, planting[p,]$lat, planting[p,]$variety, planting[p,]$seedling_rate, planting[p,]$seed_spacing, planting[p,]$speed, harvest[h,]$yield)
}
}
}
return(pairedData)
}
doesItWork=combineGPS(harvest,planting)
doesItWork
【问题讨论】: