首先,您的機場經濟是積極的,他們應該是負面的,這將甩掉結果。讓我們來解決他們如此結果更有意義:現在
airports$long <- -airports$long
,您可以使用apply
來評估所有的飛行員對每個機場。 geosphere
包有幾個函數可以計算直線距離,包括distGeo
和distHaversine
。
library(geosphere)
pilots$closest_airport <- apply(pilots[, 3:2], 1, function(x){
airports[which.min(distGeo(x, airports[, 3:2])), 'code']
})
pilots$airport_distance <- apply(pilots[, 3:2], 1, function(x){
min(distGeo(x, airports[, 3:2]))/1000 # /1000 to convert m to km
})
pilots
## names lat long closest_airport airport_distance
## 1 James 32.33513 -84.98907 STL 862.5394
## 2 Fiona 44.91322 -97.15133 Denver 855.8088
## 3 Seamus 28.84963 -96.91724 IAH 196.3559
,或者如果你希望所有的距離,而不是僅僅最小的一個,cbind
從apply
得到的矩陣:
pilots <- cbind(pilots, t(apply(pilots[, 3:2], 1, function(x){
setNames(distGeo(x, airports[, 3:2])/1000, airports$code)
})))
pilots
## names lat long closest_airport IAH DFW Denver STL
## 1 James 32.33513 -84.98907 STL 1021.6523 1131.2129 1965.6586 862.5394
## 2 Fiona 44.91322 -97.15133 Denver 1666.0359 1333.6842 855.8088 885.8480
## 3 Seamus 28.84963 -96.91724 IAH 196.3559 449.1838 1412.0664 1253.4874
翻譯成dplyr
,繼任者plyr
,
library(dplyr)
pilots %>% rowwise() %>%
mutate(closest_airport = airports[which.min(distGeo(c(long, lat), airports[, 3:2])), 'code'],
airport_distance = min(distGeo(c(long, lat), airports[, 3:2]))/1000)
## Source: local data frame [3 x 5]
## Groups: <by row>
##
## # A tibble: 3 × 5
## names lat long closest_airport airport_distance
## <fctr> <dbl> <dbl> <fctr> <dbl>
## 1 James 32.33513 -84.98907 STL 862.5394
## 2 Fiona 44.91322 -97.15133 Denver 855.8088
## 3 Seamus 28.84963 -96.91724 IAH 196.3559
或所有的距離,使用bind_cols
與上面的方法,或unnest
一個列表列,重塑:
library(tidyverse)
pilots %>% rowwise() %>%
mutate(closest_airport = airports[which.min(distGeo(c(long, lat), airports[, 3:2])), 'code'],
data = list(data_frame(airport = airports$code,
distance = distGeo(c(long, lat), airports[, 3:2])/1000))) %>%
unnest() %>%
spread(airport, distance)
## # A tibble: 3 × 8
## names lat long closest_airport Denver DFW IAH STL
## * <fctr> <dbl> <dbl> <fctr> <dbl> <dbl> <dbl> <dbl>
## 1 Fiona 44.91322 -97.15133 Denver 855.8088 1333.6842 1666.0359 885.8480
## 2 James 32.33513 -84.98907 STL 1965.6586 1131.2129 1021.6523 862.5394
## 3 Seamus 28.84963 -96.91724 IAH 1412.0664 449.1838 196.3559 1253.4874
或者更直接但不清晰,
pilots %>% rowwise() %>%
mutate(closest_airport = airports[which.min(distGeo(c(long, lat), airports[, 3:2])), 'code'],
data = (distGeo(c(long, lat), airports[, 3:2])/1000) %>%
setNames(airports$code) %>% t() %>% as_data_frame() %>% list()) %>%
unnest()
## # A tibble: 3 × 8
## names lat long closest_airport IAH DFW Denver STL
## <fctr> <dbl> <dbl> <fctr> <dbl> <dbl> <dbl> <dbl>
## 1 James 32.33513 -84.98907 STL 1021.6523 1131.2129 1965.6586 862.5394
## 2 Fiona 44.91322 -97.15133 Denver 1666.0359 1333.6842 855.8088 885.8480
## 3 Seamus 28.84963 -96.91724 IAH 196.3559 449.1838 1412.0664 1253.4874
OP正試圖確定哪些主要機場各試點最接近不是哪個飛行員距離每個機場最近 – HubertL
@HubertL哎呀,向後看。固定。 – alistaire
你往回讀它導致它向後寫 – HubertL