2017-08-20 19 views
2

複数の座標間の距離の「行列」を作成したい。好ましくは、dplyr/geosphereを使用する。私はすでに地圏パッケージがこれを提供しているのを見た。私は2つのベクトル間の距離を作成することができましたが、完全な行列を作成するのは困難です。Geosphere/dplyr:座標間の距離の行列を作成する

これは、複数の座標を持つサンプルテーブルです。

df <- data.frame(latitude = c(49.48609,-8.14671,11.28625), 
       longitude = c(8.463678,143.05793,-11.18285)) 

    latitude longitude 
1 49.48609 8.463678 
2 -8.14671 143.057930 
3 11.28625 -11.182850 

そして、これは私が探しています出力されます:私は地圏使用して試してみたが、私は2つのだけの列(Aでこのスニペットで結果間の距離を計算する方法を発見し

latitude longitude distance-latlon1 distance-latlon2 distance-latlon3     
1 49.48609  8.463678 NA     *latlon2><latlon1 *latlon3><latlon1 
2 -8.14671 143.057930 *latlon1><latlon2 NA     *latlon3><latlon2 
3 11.28625 -11.182850 *latlon1><latlon3 *latlon2><latlon3 NA 

0)。

library(geosphere) 
df$distance <- distVincentyEllipsoid(df[,c('longitude','latitude')], 
            df[,c('longitude','latitude')]) 

答えて

2

あなたはgeosphere -packageのdistm機能を必要としています。 :

# create a distance matrix 
m <- distm(df[2:1], df[2:1], fun = distVincentyEllipsoid) 

# replace the diagonal with NA 
diag(m) <- NA 

# make column names for the distance matrix 
colnames(m) <- paste0('r',1:nrow(df)) 

# bind the distance matrix to the dataframe 
cbind.data.frame(df, m) 

あなたが得る:

latitude longitude  r1  r2  r3 
1 49.48609 8.463678  NA 13792423 4606658 
2 -8.14671 143.057930 13792423  NA 17189185 
3 11.28625 -11.182850 4606658 17189185  NA 
0

我々はsfオブジェクトは経度、緯度投影(EPSG 4326)である場合に距離を計算するgeosphereから関数を使用sfパッケージからst_distance関数を使用することができます。 df2は出力例です。ここで

# Load packages 
library(dplyr) 
library(sf) 

# Create example data frame 
df <- data.frame(latitude = c(49.48609,-8.14671,11.28625), 
       longitude = c(8.463678,143.05793,-11.18285)) 

# COnvert to sf object 
df_sf <- st_as_sf(df, coords = c("longitude", "latitude")) 

# Set the projection as ESPG 4326 (long_lat) 
st_crs(df_sf) <- 4326 

# Apply the st_distance function 
dist_m <- st_distance(df_sf) 

# Combine with df 
df2 <- df %>% 
    mutate(`distance-latlon1` = as.numeric(dist_m[, 1]), 
     `distance-latlon2` = as.numeric(dist_m[, 2]), 
     `distance-latlon3` = as.numeric(dist_m[, 3])) 

# Replace 0 with NA 
df2[df2 == 0] <- NA 

df2 
    latitude longitude distance-latlon1 distance-latlon2 distance-latlon3 
1 49.48609 8.463678    NA   13792423   4606658 
2 -8.14671 143.057930   13792423    NA   17189185 
3 11.28625 -11.182850   4606658   17189185    NA 

dfdist_mを結合する別の方法です。

library(tidyr) 

# Convert dist_m to data frame 
dist_df <- dist_m %>% 
    as.table() %>% 
    as_data_frame() %>% 
    spread(Var2, n) %>% 
    select(-Var1) %>% 
    mutate_all(as.numeric) %>% 
    setNames(paste0("distance-latlon", 1:nrow(df))) 

# Combine with df 
df2 <- df %>% 
    bind_cols(dist_df) 

# Replace 0 with NA 
df2[df2 == 0] <- NA 
関連する問題