需求是使用API從openweathermap中提取資料,以下是我用來提取一個以上城市的代碼,
# Get forecast data for given city list,
# 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'/span>
#創建查詢引數
forecast_query < - list(q = city_name。 appid = "{"My API"}"。 單位="metric")
# 為給定的城市進行HTTP GET呼叫。
response<-GET(forecast_url,query=forecast_query)
# 注意,5天預測的JSON結果是一個串列。你可以列印回復來檢查結果
json_list< -內容(response,as="parsed")
結果 <- json_list$list
# 回圈json的結果
for(result in results) {
城市 <- c(city, city_name)
weather < - c(weather。 json_result$weather[[/span>1]]$main)
可見性< - c(visibility,/span> json_result$visibility)
temp < - c(temp。 json_result$main$temp)
temp_min < - c(temp_min。 json_result$main$temp_min)
temp_max < - c(temp_max。 json_result$main$temp_max)
壓力< - c(pressure。 json_result$main$pressure)
濕度< - c(humidity。 json_result$main$humidity)
wind_speed < - c(wind_speed。 json_result$wind$speed)
wind_deg < - c(wind_deg。 json_result$wind$deg)。
forecast_datetime< -c(forecast_datetime,result$dt_txt)
}。
library(zoo)
months <- as.numeric(format(as. Date(forecast_datetime),。
'%m'))
indx < - setNames( rep(c('winter'。 'spring', 'summer','秋天')。 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,
壓力=壓力,
濕度=humidity,
wind_speed=wind_speed,
wind_deg=wind_deg,
forecast_datetime=forecast_datetime,
季節=季節)
#將R串列添加到資料框中
}
# 回傳一個資料框架
return(df)
}
城市 <- c("首爾", "華盛頓,D。 C.", "巴黎", "蘇州" )
cities_weather_df <- get_weather_forecaset_by_cities(cities)
而我用openweathermap的API替換了我的 "MY API"
盡管函式和代碼的讀取沒有錯誤,但最后的資料框架卻沒有資料可用。
我怎樣才能解決這個問題?
感謝您的到來
uj5u.com熱心網友回復:
你的函式回傳的是df,而不是你剛才的data.frameweather_df
。
如果return(weather_df)不作業,我將逐行檢查,看看json_list/results是否為空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/309493.html
標籤:
上一篇:計算組內獨特組合的重量
下一篇:一口氣看完MySQL--下篇
