gpt4 book ai didi

r - 使用API​​计算R内两个机场(两列)之间的距离?

转载 作者:行者123 更新时间:2023-12-04 13:26:18 26 4
gpt4 key购买 nike

我想知道是否有一种方法可以比较机场距离(IATA代码)。有一些脚本,但是没有使用R。所以我尝试使用API​​:

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

最佳答案

这是httr包的另一种方式:

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

关于r - 使用API​​计算R内两个机场(两列)之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37572731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com