You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言循环调用API批量获取经纬度对应结果

问题:如何通过for循环逐个传入dataframe中的经纬度调用API获取结果?

我已经能用R的httr包调用API传入单个经纬度获取结果,代码如下:

library(httr)

headers = c(
        'Content-Type' = 'application/json'
      )

body = '{
        "locations": [
          {"latitude": -37.916919, "longitude": 145.146892},
        ],
        "scenarios": ["x1", "x2", "x3", "x4"],
        "hazards": ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"],
        "years": ["1", "2", "3", "4", "5", "6", "7", "8"]
      }'

res <- VERB("POST", 
                  url = "https://xxx", body = body, add_headers(headers))

现在我有一个包含多组经纬度的dataframe:

dat <-   

      structure(list(id = c(143L, 147L, 148L, 293L, 346L, 358L, 374L, 382L, 387L, 388L), 
                     latitude = c(-37.916919, -36.106951, -37.839613, -32.897738, -28.73769167, -27.8675, -28.064616, -28.016, -27.593, -27.648988), 
                     longitude = c(145.146892, 146.890143, 145.278376, 151.777484, 140.3534722, 139.6925, 139.538703, 139.692, 139.506, 139.458764)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
                                                                                                                                                             "data.frame"))

请问如何通过for循环逐个传入dataframe中的经纬度,调用API获取对应结果?


解决方案

可以按照以下步骤实现for循环遍历dat中的经纬度调用API:

  1. 初始化固定参数:提前定义请求头、API地址,以及scenarios、hazards、years这类无需变动的参数,减少循环内重复操作。
  2. 创建结果存储容器:用列表保存每个经纬度对应的API响应,方便后续统一处理。
  3. 编写循环逻辑:遍历dat的每一行,替换请求体中的经纬度,发送请求并保存解析后的结果。

完整代码如下:

library(httr)
library(jsonlite) # 用该包构建JSON请求体,避免手动拼接字符串出错

# 固定参数配置
headers <- c('Content-Type' = 'application/json')
api_url <- "https://xxx"
fixed_params <- list(
  scenarios = c("x1", "x2", "x3", "x4"),
  hazards = c("v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"),
  years = c("1", "2", "3", "4", "5", "6", "7", "8")
)

# 初始化空列表存储结果
results_list <- list()

# 遍历dataframe的每一行
for (i in 1:nrow(dat)) {
  # 获取当前行的经纬度和ID
  current_lat <- dat$latitude[i]
  current_lon <- dat$longitude[i]
  current_id <- dat$id[i]
  
  # 拼接包含当前经纬度的请求体
  request_body <- c(fixed_params, list(
    locations = list(list(latitude = current_lat, longitude = current_lon))
  ))
  
  # 转换为符合要求的JSON格式
  json_body <- toJSON(request_body, auto_unbox = TRUE)
  
  # 发送POST请求
  res <- VERB("POST", url = api_url, body = json_body, add_headers(headers))
  
  # 解析API响应(可根据实际返回格式调整)
  parsed_res <- fromJSON(content(res, "text"))
  
  # 将结果与对应ID关联后存入列表
  results_list[[as.character(current_id)]] <- parsed_res
  
  # 可选:添加延迟,避免请求过于频繁触发API限流
  Sys.sleep(1)
}

# 可选:将结果列表转换为dataframe,方便查看和分析
results_df <- dplyr::bind_rows(results_list, .id = "id")

注意事项:

  • 使用jsonlite构建请求体比手动拼接字符串更可靠,能避免JSON语法错误。
  • Sys.sleep(1)用于控制请求频率,具体延迟时间可根据API的限流规则调整。
  • 若API返回二进制或其他非JSON格式数据,需调整响应解析的逻辑。

内容的提问来源于stack exchange,提问作者89_Simple

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:48:46