我试图根据条件从另一个数据帧中的值替换数据帧中的值 .
两个数据都包含纬度,经度和高度,但其中一个更短 . 我想从较短的数据帧(5103行)中选择任意点,在第二个(188426行)上找到纬度和经度上最接近的值(通过计算距离),然后用最长的数据帧替换最长数据帧的高度值 . 较短的高度 .
第一个数据框是下面代码中的topo.rams,第二个是topo.msg . 最终目的是用topo.rams中的高度值替换topo.msg中的高度
topo.rams:
longitud,latitud,tempc,u,v,w,relhum,speed,topo
-1.7107, 38.1464, 18.2412, -6.1744, -0.3708, 0.0000, 58.6447, 6.3584,460.5908
-1.7107, 38.1734, 18.5915, -5.7757, -0.3165, 0.0000, 61.8492, 5.9840,416.0403
topo.msg
height,longitud,latitud
448.0, 1.70, 38.14
402.0, 1.70, 38.18
和所需的输出(topo.msg修改)
height,longitud,latitud
460.5908, 1.70, 38.14
416.0403, 1.70, 38.18
和使用的代码
#lectura de datos
topo.msg=read.csv("MSG_DEM.txt",sep=",",header=FALSE)
colnames(topo.msg) <- c("topoMSG","longitud","latitud")
topo.rams=read.csv("topografia-rams.txt",sep=",",header=TRUE)
# número de estaciones a tratar
puntos.rams=dim(topo.rams)[1]
puntos.msg=dim(topo.msg)[1]
# Localización del punto de MSG más próximo a la estación.
# Se calcula la distancia a partir de las coordenadas lat-lon
topo.temp=data.frame()
for(i in 1:puntos.rams)
{
for(j in 1:puntos.msg)
{
dlon<-topo.rams$longitud[i]-topo.msg$longitud
if ( dlon < 0.5 && dlat < 0.5) {
dlat<-topo.rams$latitud[i]-topo.msg$latitud
if ( dlat < 0.5) {
n1<-n1+1
distancia=sqrt(dlon*dlon+dlat*dlat)
}
}
indexj=which.min(distancia)
}
topo.msg$topo[indexj] = topo.rams$topo[i]
}
这段代码似乎运行但需要很长时间 . 我还尝试用Geographic distance between 2 lists of lat/lon coordinates中的帖子创建一个带地圈包的距离矩阵但是R抱怨分配3.6 Gb .
我该如何解决这个问题?我想优化循环或使用距离矩阵 . 当然,必须有一种更清洁,更有效的方法来计算距离 .
提前致谢
1 回答
从Patric的评论中我从循环切换到矩阵/向量计算 . 现在代码正在运行,更简单,更高效 .
可能有一种更优雅的方式来进行此计算 . 我很感激任何意见 .