我正在尝试使用 DARKSKY API 检索 R 中 100 个城市的历史天气数据。
以下代码可用于获取 1 个城市的历史数据,但是我在创建循环函数以遍历 100 个纬度和经度的列表并输出数据时遇到问题。
weather <- function(Long,Lat)
{ a <-seq(Sys.Date()-10, Sys.Date(), "1 day") %>%
map(~get_forecast_for(Long,Lat,.x, units = 'si')) %>%
map_df('daily')
write.csv(a,"blah blah")
}
weather(52.6983,-1.0735)
我最初的想法是上传包含我需要的所有经度和纬度的 csv 文件。将它们设置为变量,然后将它们映射到上面的函数。
data <- read.csv("blah blah")
Long <- data$Longitude
Lat <- data$Latitude
map(c("Long","Lat"),weather)
但它不断带回错误消息。
有人可以帮忙吗?
谢谢
你快到了。get_forecast_for
按行迭代函数需要做一些事情。从purrr
包中,该pmap
函数适用于按行重复函数,而该imap
函数可用于按行中的单元格重复函数。
使用这种方法,我编写了两个函数:weather_at_coords
和weather
. weather_at_coords
用于向 DarkSkyAPI 发送请求,获取给定时间范围内(即过去 10 天)特定位置的天气。该weather
函数用于逐行重复该函数。
我看到您想要嵌套对象daily
,因此编写了从响应中提取该列表的函数。我假设您还想要 data.frame 中的结果,所以我添加了bind_rows
. 我添加了一个列,id
以便可以将行正确链接到某个位置(或者您可以添加任何您喜欢的列)。
# pkgs
library(tidyverse)
library(darksky)
# set API Key: free from https://darksky.net/dev
darksky::darksky_api_key()
# Forecast at a given point and time period
weather_at_coords <- function(...) {
d <- rlang::list2(...)
time <- seq(Sys.Date()-10, Sys.Date(), "1 day")
response <- imap(time, ~ darksky::get_forecast_for(d$lat, d$lon, .x, units = "si")[["daily"]])
out <- bind_rows(response) %>% mutate(id = d$id)
return(out)
}
# primary function (iterates across rows)
weather <- function(data) {
result <- pmap(data, ~ weather_at_coords(...))
return(bind_rows(result))
}
# sample data
d <- data.frame(
id = c("a", "b"),
lat = c(37.8267,34.8267),
lon = c(-122.423, -120.423)
)
# run
x <- weather(d)
x
笔记
rlang
安装了软件包lat
和lon
变量名称。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句