用户集R中的测地距离函数

用户集R中的测地距离函数,r,function,social-networking,distance,euclidean-distance,R,Function,Social Networking,Distance,Euclidean Distance,我试图计算社交网络用户之间的测地距离。假设我有两个用户U1和U2,我如何在R中声明函数,以使测地距离函数返回由1000个用户组成的大型数据集中任意两个用户之间的距离 d <- function (U1(lat1,lon1),U2(lat2,lon2)) { rad <- pi/180 a1 <- lat1 * rad a2 <- lon1 * rad b1 <- lat2 * rad b2 <- lon2 * rad dlon <

我试图计算社交网络用户之间的测地距离。假设我有两个用户U1和U2,我如何在R中声明函数,以使测地距离函数返回由1000个用户组成的大型数据集中任意两个用户之间的距离

d <- function (U1(lat1,lon1),U2(lat2,lon2))
{
  rad <- pi/180
  a1 <- lat1 * rad
  a2 <- lon1 * rad
  b1 <- lat2 * rad
  b2 <- lon2 * rad
  dlon <- b2 - a2
  dlat <- b1 - a1
  a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
  c <- 2 * atan2(sqrt(a), sqrt(1 - a))
  R <- 6378.145
  d <- R * c
  miles <- d*0.621
  return(c(d,miles))
}

d这个库看起来很有前途:

library(geosphere)
distm(c(lon1,lat1), c(lon2,lat2))
有两个矩阵:

distm(
  matrix( c(
    1, 3, 
    2, 2,
    3, 1
  ), nrow = 3, ncol = 2),

  matrix( c(
    4, 6, 
    5, 5,
    6, 4,
    3, 1
  ), nrow = 4, ncol = 2)
)
n个用户的矩阵及其之间的距离: #用户数
n谢谢你的回答。它工作得很好,但是我可以不用rnorm来做吗?有什么具体的原因吗?对于lat,r范数的平均值是46,对于long,r范数的平均值是14。我使用rnorm只是作为(随机)数据生成器。在您的情况下,lat和lon向量将从某些数据库生成。我已经从一个数据集中读取了我的lon1、lat1,类似于lon2,lat2从另一个数据集中读取到上面的distm函数中。那么,我将在位置上读取什么样的纬度。我有点困惑,因为在#位置中只有一个lat lon,而cmat matrixy可以用两个矩阵调用distm。或者有两点类似:
distm(c(lon1,lat1),c(lon2,lat2))
是的,我已经调用了它并成功地执行了第2行,但是我对cmat c(lat,lon)部分表示怀疑,因为我有两个lon,lat,我如何执行c(lat,lon)或者应该是cmat
# positions
lat <- rnorm(n, 46, 1) 
lon <- rnorm(n, 14, 1) 

#distm also accepts a matrix (2 x n):
cmat <- matrix( c(lat, lon), nrow = n, ncol = 2)
distm(cmat)