Skip to content

Instantly share code, notes, and snippets.

@richfitz
Created June 17, 2013 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save richfitz/5795029 to your computer and use it in GitHub Desktop.
Save richfitz/5795029 to your computer and use it in GitHub Desktop.
Download some weather data from openweathermap.org
library(RCurl)
library(rjson)
url.base <- function()
"http://api.openweathermap.org/data"
city.to.id <- function(city, country="AU") {
url <- sprintf("%s/2.5/find?q=%s", url.base(), city)
res <- fromJSON(getURLContent(url))
if (!is.null(country)) {
ok <- sapply(res$list, function(x) x$sys$country %in% country)
res$list <- res$list[ok]
}
n <- length(res$list)
if (n < 1)
stop("Failed to find information for city", city)
if (n > 1)
warning("More than one possible hit, returning first")
res$list[[1]]$id
}
from.kelvin <- function(x) x - 273.15
past.weather <- function(id, by="day", n=30) {
by <- match.arg(by, c("day", "hour", "tick"))
url <- sprintf("%s/2.1/history/city/?id=%d?type=%s&cnt=%d",
url.base(), id, by, n)
res <- fromJSON(getURLContent(url))
dat <- res$list
temp <- t(sapply(dat, function(x)
from.kelvin(c(temp=x$main$temp,
temp.min=x$main$temp_min,
temp.max=x$main$temp_max))))
time <- as.POSIXct(sapply(dat, function(x) x$dt),
origin="1970-01-01", tz="UTC+10")
data.frame(time=time, temp)
}
cities <- c("Melbourne", "Sydney", "Brisbane", "Cairns")
ids <- sapply(cities, city.to.id)
res <- lapply(ids, past.weather, n=100)
names(res) <- cities
path <- "data"
dir.create(path, recursive=TRUE, showWarnings=FALSE)
for (city in cities)
write.csv(res[[city]], file.path(path, paste0(city, ".csv")),
row.names=FALSE)
@dudfoKim
Copy link

thank U :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment