在R中经纬度合并 [英] Merge by lat/lon in R

查看:88
本文介绍了在R中经纬度合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题类似于合并两个数据帧,两个数据帧的坐标都基于最近的位置.我想按纬度和经度合并R中的两个数据框:

My question is similar to Merging two data frames, both with coordinates based on the closest location. I would like to merge two dataframes in R by latitude and longitude:

Dataframe 1
structure(list(lat = c(54L, 55L, 51L, 54L, 53L, 50L, 47L, 51L, 
49L, 54L), lon = c(14L, 8L, 15L, 7L, 6L, 5L, 13L, 5L, 13L, 11L
), PPP2000_40 = c(4606, 6575, 6593, 7431, 9393, 10773, 11716, 
12226, 13544, 14526)), .Names = c("lat", "lon", "PPP2000_40"), row.names =c(6764L, 8796L, 8901L, 9611L, 11649L, 12819L, 13763L, 14389L, 15641L, 
16571L), class = "data.frame")

# Dataframe 2
structure(list(lat = c(47, 47, 47, 47, 47, 47, 48, 48, 48, 48
), lon = c(7, 8, 9, 10, 11, 12, 7, 8, 9, 10), GDP = c(19.09982, 
13.31977, 14.95925, 6.8575635, 23.334565, 6.485748, 24.01197, 14.30393075, 21.33759675, 9.71803675)), .Names = c("lat", "lon", "GDP"), row.names = c(NA,  10L), class = "data.frame")

如何将它们合并到R中?谢谢!

How can I merge them in R? Thanks!

推荐答案

基于此帖子:

library(geosphere)
mat <- distm(df1[,c('lon','lat')], df2[,c('lon','lat')], fun=distVincentyEllipsoid)
df1$GDP <- df2$GDP[apply(mat, 1, which.min)]

结果是:

> df1
      lat lon PPP2000_40       GDP
6764   54  14       4606  9.718037
8796   55   8       6575 14.303931
8901   51  15       6593  9.718037
9611   54   7       7431 24.011970
11649  53   6       9393 24.011970
12819  50   5      10773 24.011970
13763  47  13      11716  6.485748
14389  51   5      12226 24.011970
15641  49  13      13544  6.485748
16571  54  11      14526  9.718037

这篇关于在R中经纬度合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆