Search code examples
rhttphttprequestopenweathermap

How to get a day weather forecast for a list of cities using R?


I tried to get the date frame using this function but I cant get it right, as I am trying to Write a function to return a data frame containing 5-day weather forecasts for a list of cities but I do not know what is missing. Here I using openweathermap.org for the weather data. Thanks.

# Get forecast data for a given city list
get_weather_forecaset_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'
        # Create query parameters
        forecast_query <- list(q = city_name, appid = "b0847c4a1554d3c63d46d0e9249500f0", units="metric")
        # Make HTTP GET call for the given city
        responce<- GET(forecast_url, query= forecast_query)
        json_result <- content(responce, as="parsed")
        
        # Note that the 5-day forecast JSON result is a list of lists. You can print the reponse to check the results
         result <- json_result
        
        # Loop the json result
        for(result in results) {
            city <- c(city, city_name)
            
        }
        
        # Add the R Lists into a data frame
         # $weather is also a list with one element, its $main element indicates the weather status such as clear or rain
city  <- c(result$city$name)       
weather <- c( result$weather[[1]]$main)
# Get Visibility
visibility <- c( result$visibility)
# Get current temperature 
temp <- c(result$main$temp)
# Get min temperature 
temp_min <- c( result$main$temp_min)
# Get max temperature 
temp_max <- c( result$main$temp_max)
# Get pressure
pressure <- c( result$main$pressure)
# Get humidity
humidity <- c(result$main$humidity)
# Get wind speed
wind_speed <- c( result$wind$speed)
# Get wind direction
wind_deg <- c( result$wind$deg)
weather_data_frame <- data.frame(city,
                                 weather,
                                 visibility, 
                                 temp, 
                                 temp_min, 
                                 temp_max, 
                                 pressure, 
                                 humidity, 
                                 wind_speed, 
                                 wind_deg)

    }
    
    # Return a data frame
    return(df)
    
}

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

Solution

  • I was finally able to do it after long time and multiple tries, here is the complete code, you just need to add your API Key

    # Get forecast data for a given city list
    get_weather_forecaset_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"
        # Create query parameters
        forecast_query <- list(q = city_name, appid = "***API Key***", units = "metric")
        # Make HTTP GET call for the given city
        forecast_response <- GET(forecast_url, query = forecast_query)
        # Note that the 5-day forecast JSON result is a list of lists. You can print the response to check the results
        forecast_json_list <- content(forecast_response, as = "parsed")
        results <- forecast_json_list$list
        result <- c(1:40)
    
        # Loop the json result
        for (x in result) {
          city <- c(city, city_name)
          # $weather is also a list with one element, its $main element indicates the weather status such as clear or rain
          weather <- c(weather, results[[x]]$weather[[1]]$main)
          # Get Visibility
          visibility <- c(visibility, results[[x]]$visibility)
          # Get current temperature
          temp <- c(temp, results[[x]]$main$temp)
          # Get min temperature
          temp_min <- c(temp_min, results[[x]]$main$temp_min)
          # Get max temperature
          temp_max <- c(temp_max, results[[x]]$main$temp_max)
          # Get pressure
          pressure <- c(pressure, results[[x]]$main$pressure)
          # Get humidity
          humidity <- c(humidity, results[[x]]$main$humidity)
          # Get wind speed
          wind_speed <- c(wind_speed, results[[x]]$wind$speed)
          # Get wind direction
          wind_deg <- c(wind_deg, results[[x]]$wind$deg)
          # Get forcast_datetime
          forecast_datetime <- c(forecast_datetime, results[[x]]$dt_txt)
        }
    
        # Add the R Lists into a data frame
        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
        )
      }
    
      # Return a data frame
      return(df)
    }