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

R调用OpenWeatherMap API提取天气数据返回空数据框如何修复

排查及修复方案

排查步骤

  • 核心返回值逻辑错误:函数开头初始化了空数据框df,但整段代码从未对df进行赋值操作,最终直接返回df,必然返回空结果。
  • 变量引用错误:内层循环遍历单条预报数据result时,错误引用了不存在的变量json_result,实际要读取的字段都来自当前循环的result对象。
  • 向量初始化逻辑缺失:存储字段的city、weather等临时向量没有提前初始化,每次循环拼接会存在变量找不到的报错风险,且多城市循环时不会清空临时向量,会出现数据重复累加的问题。
  • 结果合并逻辑缺失:单城市处理完生成的weather_df没有合并到全局结果中,多城市数据无法汇总。
  • 可选校验补充:可在API请求后增加响应状态码校验,判断返回值是否为200,排除API密钥无效、城市名识别失败等调用错误。
  • 小问题:原函数名拼写错误get_weather_forecaset_by_cities,少了字符t,同时依赖包加载放在循环内部,会重复执行加载逻辑,建议移到脚本开头。

修复后的完整代码

# 提前加载依赖包
library(httr)
library(zoo)

# Get forecast data for a given city list
get_weather_forecast_by_cities <- function(city_names){
  # 初始化全局结果数据框
  df <- data.frame()
  for (city_name in city_names){
    # Forecast API URL
    forecast_url <- 'https://api.openweathermap.org/data/2.5/forecast'
    # 创建查询参数,替换为自己的有效API密钥
    forecast_query <- list(q = city_name, appid = "你的有效API密钥", units="metric")
    # 发起HTTP GET请求
    response <- GET(forecast_url, query=forecast_query)
    # 校验请求是否成功,失败则跳过当前城市
    if (status_code(response) != 200) {
      warning(paste(city_name, "数据请求失败,跳过该城市"))
      next
    }
    json_list <- content(response, as="parsed")
    results <- json_list$list
    
    # 初始化当前城市的临时存储向量
    city <- c()
    weather <- c()
    visibility <- c()
    temp <- c()
    temp_min <- c()
    temp_max <- c()
    pressure <- c()
    humidity <- c()
    wind_speed <- c()
    wind_deg <- c()
    forecast_datetime <- c()
    
    # 遍历当前城市的所有预报结果
    for(result in results) {
      city <- c(city, city_name)
      weather <- c(weather, result$weather[[1]]$main)
      visibility <- c(visibility, ifelse(is.null(result$visibility), NA, result$visibility))
      temp <- c(temp, result$main$temp)
      temp_min <- c(temp_min, result$main$temp_min)
      temp_max <- c(temp_max, result$main$temp_max)
      pressure <- c(pressure, result$main$pressure)
      humidity <- c(humidity, result$main$humidity)
      wind_speed <- c(wind_speed, result$wind$speed)
      wind_deg <- c(wind_deg, result$wind$deg)
      forecast_datetime <- c(forecast_datetime, result$dt_txt)
    }
    # 计算季节
    months <- as.numeric(format(as.Date(forecast_datetime), '%m'))
    indx <- setNames(rep(c('winter', 'spring', 'summer', 'fall'), each=3), c(12,1:11))
    season <- unname(indx[as.character(months)])
    # 生成单城市数据框
    weather_df <- data.frame(
      city=city,
      weather=weather, 
      visibility=visibility, 
      temp=temp,
      temp_min=temp_min, 
      temp_max=temp_max, 
      pressure=pressure, 
      humidity=humidity, 
      wind_speed=wind_speed, 
      wind_deg=wind_deg,
      forecast_datetime=forecast_datetime,
      season=season
    )
    # 合并到全局结果
    df <- rbind(df, weather_df)
  }
  # 返回最终汇总数据
  return(df)
}

cities <- c("Seoul", "Washington, D.C.", "Paris", "Suzhou")
cities_weather_df <- get_weather_forecast_by_cities(cities)

内容的提问来源于stack exchange,提问作者Yousef Yahia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:39:01