2016-06-01 6 views
6

공항 거리 (IATA 코드)를 비교할 수있는 방법이 있는지 궁금합니다. 이 일부 스크립트는하지만, R.을 사용하지 않는 것은 그래서 나는 시도 그와 API를 사용하여 :API를 사용하여 R 내의 두 공항 (두 열) 간의 거리를 계산 하시겠습니까?

developer.aero

예 데이터 :

library(curl) # for curl post 

departure <- c("DRS","TXL","STR","DUS","LEJ","FKB","LNZ") 
arrival <- c("FKB","HER","BOJ","FUE","PMI","AYT","FUE") 
flyID <- c(1,2,3,4,5,6,7) 
df <- data.frame(departure,arrival,flyID) 

    departure arrival flyID 
1  DRS  FKB  1 
2  TXL  HER  2 
3  STR  BOJ  3 
4  DUS  FUE  4 
5  LEJ  PMI  5 
6  FKB  AYT  6 
7  LNZ  FUE  7 

api<- curl_fetch_memory("https://airport.api.aero/airport/distance/DRS/FUE?user_key=d805e84363494ca03b9b52d5a505c4d1") 

cat(rawToChar(api$content)) 

callback({"processingDurationMillis":0,"authorisedAPI":true,"success":true,"airline":null,"errorMessage":null,"distance":"3,416.1","units":"km"}) 
DRS 출발 및 FUE 도착 공항에 해당

그래서 나는 df을 반복하여 URL에 붙여 넣습니다. 그러나 그는 R 위해 어떻게 든 어려운 보인다 - 신참

df$distance<- list(length = nrow(df)) 
for (i in 1:nrow(df)){ 
    url <- paste0("https://airport.api.aero/airport/distance/", i, "FUE ?user_key=d805e84363494ca03b9b52d5a505c4d1") 
    myData[[i]] <- read.table(url, header=T,sep="|") 
} 

원하는 출력 :

departure arrival flyID distance 
1  DRS  FKB  1 1000 
2  TXL  HER  2 499 
3  STR  BOJ  3 300 
4  DUS  FUE  4 200 
5  LEJ  PMI  5 586 
6  FKB  AYT  6 10292 
7  LNZ  FUE  7 3939 
+1

'read.table'을 실행할 때 거리를 얻었습니까? 질문은 data.frame에 저장하는 방법입니다. 아니면 당신은 공항의 좌표계 만 얻으십니까? 당신의 질문은 그것들을 거리로 변형시키는 방법에 관한 것입니까? 또는 IATA 코드를 geocoordinates에 연결하는 것에 대한 질문입니까? – Qaswed

+0

명확화 요청에 대한 긍정적 인 응답이있는 경우 closevote 제안에 참여하지 않았지만 코드의 두 번째 섹션에서 throw 된 오류로 인해 실제로 무엇이 요청되는지 명확하지 않습니다. –

답변

6

여기 자유롭게 데이터베이스에서 사용할 수있는 공항의 좌표를 사용하여 API를하지 않고이 작업을 수행 할 수 있습니다

library(httr) 

callAPI <- function(from, to) { 
    res <- GET("https://airport.api.aero", 
      path = paste0("airport/distance/", from, "/", to), 
      query = list(user_key = "d805e84363494ca03b9b52d5a505c4d1")) 
    stop_for_status(res) 
    return(content(res, encoding = "UTF-8")) 
} 


test <- callAPI("DRS", "FKB") 
# test 
test$distance 
# [1] "484.6" 

for (i in 1:nrow(df)) { 
    from = df[i, "departure"] 
    to = df[i, "arrival"] 
    df[i, "distance"] <- callAPI(from, to)$distance 
} 

# departure arrival flyID distance 
# 1  DRS  FKB  1 484.6 
# 2  TXL  HER  2 2,131.8 
# 3  STR  BOJ  3 1,575.0 
# 4  DUS  FUE  4 3,066.3 
# 5  LEJ  PMI  5 1,512.4 
# 6  FKB  AYT  6 2,264.2 
# 7  LNZ  FUE  7 3,258.0 

전체 결과를 얻으려면 다음을 사용할 수 있습니다.

all_results <- mapply(function(x,y) { callAPI(x,y) }, df$departure, df$arrival) 
cbind(df, t(all_results)) 
# departure arrival flyID processingDurationMillis authorisedAPI success airline errorMessage distance units 
# 1  DRS  FKB  1      0   TRUE TRUE NULL   NULL 484.6 km 
# 2  TXL  HER  2      0   TRUE TRUE NULL   NULL 2,131.8 km 
# 3  STR  BOJ  3      0   TRUE TRUE NULL   NULL 1,575.0 km 
# 4  DUS  FUE  4      0   TRUE TRUE NULL   NULL 3,066.3 km 
# 5  LEJ  PMI  5      0   TRUE TRUE NULL   NULL 1,512.4 km 
# 6  FKB  AYT  6      0   TRUE TRUE NULL   NULL 2,264.2 km 
# 7  LNZ  FUE  7      1   TRUE TRUE NULL   NULL 3,258.0 km 
+0

굉장합니다. 고맙습니다!! –

+0

aiports 사이의 거리가 "NULL"인 경우 for 루프를 조정하는 방법에 대한 추가 정보를 하나씩 물어볼 수 있습니까? 루프가 멈추는 것 같아요. 다시 감사합니다! –

+1

@MichaerMacher이 질문을 새로운 질문으로 권할 것입니다. 또한'for' 루프의 마지막 두 줄을 다음과 같이 바꿀 수 있습니다 :'distance <- ifelse (callAPI (from, from) $ distance), NA, callAPI (from, to) $ distance) '및'df [i, "distance"] <- distance'. 이렇게하면 조사 할 'NA'를 반환합니다. – JasonAizkalns

1

무엇 당신의 API 호출을 통해 다음 루프에 대해?

df$distance <- 0 

for (i in nrow(df)){ 
    drs <- df[i,]$departure 
    fue <- df[i,]$arrival 
    url <- paste0("https://airport.api.aero/airport/distance/", drs, "/", fue, "?user_key=4e816a2bf391f8379df1c42d2762069e") 
    api <- curl_fetch_memory(url) 
    text <- rawToChar(api$content) 
    distance <- as.numeric(gsub(',','',substr(text,regexpr('distance',text)+11,regexpr('units',text)-4))) 
    df[1,]$distance <- distance 
} 

df 
7

당신은 바로 여기에 httr 패키지와 다른 방법의 https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat

## Import airport data 
airports <- read.csv("https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat", header = F) 

library(geosphere) 
## Calculate matrix of differences in km 
distance.matrix <- distm(x = airports[,c("V8", "V7")], y = airports[,c("V8", "V7")])/1000 
## This may take a while, and will generate a matrix 8107 by 8107, about 0.5gb in size. 

## Rename dimensions to airport codes 
rownames(distance.matrix) <- airports$V5 
colnames(distance.matrix) <- airports$V5 

## Example: km between Gatwick and Heathrow 
distance.matrix["LGW", "LHR"] 
[1] 41.24091