使用st_distance()并在dataframe中获取具有位置名称的数据

niwlg2el  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(113)

代码参考https://www.r-bloggers.com/2019/10/geographic-distance/

library(maps)
library(sf) 
library(tidyverse)
library(units)
library(rnaturalearth)

cities1 <- st_as_sf(world.cities, coords = c("long", "lat"), crs = 4326)
china<-filter(cities1)
capitals <- filter(cities1, capital == 1)
capitals <- mutate(capitals, city_country = str_c(name, " (", country.etc, ")"))
dist_amsterdam <- st_distance(slice(capitals), 
                              slice(capitals))

结果是值,但不是数据框。我需要的是一个具有country.ect列和行的数据框。

country.ect  Jordan United ArbEmirates ...

Jordan   dist_amsterdam result

United ArbEmirates

...
6bc51xsx

6bc51xsx1#

如果我正确地理解了你的目标,即一个完整的表,每个大写字母之间的所有距离,下面应该会导致预期的结果。

library(maps)
library(sf) 
#> Linking to GEOS 3.11.0, GDAL 3.5.2, PROJ 9.0.1; sf_use_s2() is TRUE
library(tidyverse)
library(units)
#> udunits database from /usr/share/udunits/udunits2.xml
library(rnaturalearth)
library(tibble)

cities1 <- st_as_sf(world.cities, coords = c("long", "lat"), crs = 4326)
china<-filter(cities1)
capitals <- filter(cities1, capital == 1)
capitals <- mutate(capitals, city_country = str_c(name, " (", country.etc, ")"))

distance <- st_distance(capitals, 
                        capitals) %>% 
  tibble::as_tibble() %>% 
  dplyr::mutate(capitals = capitals$city_country) %>% 
  dplyr::select(capitals, dplyr::everything())

colnames(distance) <- c("capitals", capitals$city_country)

distance
#> # A tibble: 230 × 231
#>    capitals           `'Amman (Jordan)` Abu Dhabi (United Ar…¹ `Abuja (Nigeria)`
#>    <chr>                            [m]                    [m]               [m]
#>  1 'Amman (Jordan)                   0                1984817.          3896440.
#>  2 Abu Dhabi (United…          1984817.                     0           5273454.
#>  3 Abuja (Nigeria)             3896440.               5273454.                0 
#>  4 Accra (Ghana)               4762499.               6180174.           906821.
#>  5 Adamstown (Pitcai…         18451168.              19559382.         15169967.
#>  6 Addis Abeba (Ethi…          2565025.               2387066.          3465106.
#>  7 Agana (Guam)               10921307.               9429213.         14698578.
#>  8 Algiers (Algeria)           3050854.               5035537.          3096002.
#>  9 Alofi (Niue)               17062364.              15420581.         18873768.
#> 10 Amsterdam (Nether…          3374492.               5163124.          4806957.
#> # ℹ 220 more rows
#> # ℹ abbreviated name: ¹​`Abu Dhabi (United Arab Emirates)`
#> # ℹ 227 more variables: `Accra (Ghana)` [m], `Adamstown (Pitcairn)` [m],
#> #   `Addis Abeba (Ethiopia)` [m], `Agana (Guam)` [m], `Algiers (Algeria)` [m],
#> #   `Alofi (Niue)` [m], `Amsterdam (Netherlands)` [m],
#> #   `Andorra la Vella (Andorra)` [m], `Ankara (Turkey)` [m],
#> #   `Antananarivo (Madagascar)` [m], `Apia (Samoa)` [m], …

创建于2023-04-22使用reprex v2.0.2

相关问题