所有点到第一个点的距离 [英] Distance between all the points to the first point

查看:46
本文介绍了所有点到第一个点的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在街道上有一些点,我正在尝试计算所有点与街道上第一个点之间的距离

I have points on a street, and Im trying to calculate the distance between all the points and the first point in the street

这是我的 sf 对象:

Here is my sf object:

library(rgeos)
library(rgdal)
library(sf)
 #I actually have multiple points on a segment of 5 Km
df <- data.frame(lon = c(-121.95, -121.96, -121.97, -121.98), lat = c(37.35,37.36,37.37,37.38)) 
coordinates(df) <- c("lon", "lat")
proj4string(df) <- CRS("+init=epsg:4326") 
df_sf <- st_as_sf(df) %>% st_transform(3488)

我试过 st_distance 但距离不正确.我得到的是让每一个点都到街道的起点直到终点.所以基本上它必须从 0 到 5000m.

I tried st_distance but the distance is not correct. What I sould get is to have each point distance to the begining of the street until the end. So basically it has to go from 0 to the 5000m.

推荐答案

如果在 st_distance() 中加入 by_element 参数,我想你会得到结果您正在寻找.如果您将 by_element 保留为 FALSE(默认值),您将得到一个矩阵.

If you add the by_element argument to st_distance(), I think you'll get the result you're looking for. If you leave by_element as FALSE (the default), you'll get a matrix instead.

st_distance(x = df_sf, 
            y = df_sf[1,], 
            by_element = TRUE)

Units: [m]
[1]    0.000 1420.606 2841.141 4261.604

请注意,距离与其他答案 b/c df_sf 的投影略有不同.如果我们使用未投影的 df 对象,则距离匹配:

Note that the distances differ slightly from the other answer b/c df_sf is projected. If we use the unprojected df object, the distances match:

st_distance(x = df, 
            y = df[1,], 
            by_element = T)

Units: [m]
[1]    0.000 1420.098 2840.125 4260.079

编辑回复评论 re: order

距离将按照您的数据框的顺序排列.在您的示例中,它们碰巧按升序排列.

The distances will be in the order of your dataframe. They happen to be in ascending order in your example.

您可以将距离添加为新列,然后使用 dplyr 对该列进行排序.请注意,这里需要 by_element 参数,因为新列不接受矩阵作为值.

You could add the distances as a new column and then sort on that column using dplyr. Note that the by_element argument is necessary here, as the new column won't accept a matrix as a value.

library(dplyr)
df_sf %>% 
  mutate(dist_to_first = st_distance(x = df_sf, 
                                     y = df_sf[1,], 
                                     by_element = TRUE)) %>% 
  arrange(dist_to_first)

Simple feature collection with 4 features and 1 field
geometry type:  POINT
dimension:      XY
bbox:           xmin: -175068.7 ymin: -72303.08 xmax: -172485.1 ymax: -68913.94
epsg (SRID):    3488
proj4string:    +proj=aea +lat_1=34 +lat_2=40.5 +lat_0=0 +lon_0=-120 +x_0=0 +y_0=-4000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
  dist_to_first                    geometry
1     0.000 [m] POINT (-172485.1 -72303.08)
2  1420.606 [m] POINT (-173346.5 -71173.46)
3  2841.141 [m] POINT (-174207.7 -70043.74)
4  4261.604 [m] POINT (-175068.7 -68913.94)

这篇关于所有点到第一个点的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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