【问题标题】:Distance Matrix Using R and CSV coordinates of Postal Codes使用邮政编码的 R 和 CSV 坐标的距离矩阵
【发布时间】:2019-12-18 22:01:51
【问题描述】:

我是 R 语言的普通用户,我有一个包含 800000 个加拿大邮政编码坐标(经度、纬度)的数据集。

我附上了一个 CSV 文件,其中包含一个名为 question.csv 的示例。

TariffZone<-c("CAAL1","CAAL2","CAAL3","CAAL3")
latitude<-c(51.15701,51.91826,50.80972,50.76358)
longitude<-c(-110.206392,-110.146722,-110.7003,-110.568045)
elevation<-c(300,400,450,450)
d<-data.frame(TariffZone,latitude,longitude,elevation)

我正在尝试获取一个表格,其中包含关税区之间的所有公里距离(平均每个邮政编码的坐标)

我看过一个相关的问题:R distance matrix build

不幸的是,我无法用给定的答案解决我的问题,这是我的代码:

d<-read.csv("question.csv", header=TRUE)
head(d)

d2<-d %>% 
  group_by(TariffZone) %>%
  summarise(latitude_mean=mean(latitude),longitude_mean=mean(longitude),elevation_mean=mean(elevation)) %>%
  dplyr::mutate_if(is.numeric, format, 4) %>%
  ungroup()
head(d2)

d3<-data.frame(d2$longitude_mean,d2$latitude_mean)
head(d3)

distable<-dist(cbind(d2$longitude_mean,d2$latitude_mean),cbind(d2$longitude_mean,d2$latitude_mean),method=euclidean)

harvesine<-function(lat1,lat2){
  newVar<-acos(sin(lat1*3.14159265359/180)*sin(lat2*3.14159265359/180) + cos(lat1*3.14159265359/180)*cos(lat2*3.14159265359/180)*cos(lon2*3.14159265359/180-lon1*3.14159265359/180) ) * 6371000} 

如果我忘记添加任何信息或者我必须准确提出我的问题,请不要犹豫。

奖励:如果有办法可以使用代码中的 harvesine 公式而不是欧几里得公式,并且可以将此表导出回 csv 文件

【问题讨论】:

标签: r distance


【解决方案1】:

来自?distm

x 点的经度/纬度。可以是两个数字的向量、2 列的矩阵(第一个是经度,第二个是纬度)或 SpatialPoints* 对象

library(geosphere)
distm(d[c("longitude", "latitude")])
#          [,1]      [,2]      [,3]      [,4]
# [1,]     0.00  84796.69  51919.29  50608.72
# [2,] 84796.69      0.00 129215.81 131775.10
# [3,] 51919.29 129215.81      0.00  10645.63
# [4,] 50608.72 131775.10  10645.63      0.00

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2013-06-20
    • 2011-04-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多