Created
May 19, 2016 15:30
-
-
Save daijiang/b472b6324100f86db22e6e9f0bc120e5 to your computer and use it in GitHub Desktop.
To get historical climate data for a specific date.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(weatherData) | |
library(plyr) | |
library(dplyr) | |
library(ggplot2) | |
library(tidyr) | |
years = seq(1948, 2015, 1) | |
days = "-03-08" | |
alldays = paste0(years, days) | |
dat_climate = list(length = length(alldays)) | |
for(x in alldays){ | |
dat_climate[[which(x == alldays)]] = | |
getWeatherForDate("KMSN", x, opt_all_columns = T) | |
} | |
for(i in 1:length(dat_climate)){ | |
dat_climate[[i]]$Date = as.Date(dat_climate[[i]]$Date) | |
} | |
dat_climate = ldply(dat_climate) | |
str(dat_climate) | |
dat_climate_df = select(dat_climate, Date, Max_TemperatureF, Mean_TemperatureF, | |
Min_TemperatureF, Max_Wind_SpeedMPH, Mean_Wind_SpeedMPH, | |
PrecipitationIn) %>% | |
mutate(year = years) %>% | |
bind_rows(data.frame(Date = as.Date("2016-03-08"), Max_TemperatureF = 64, | |
Mean_TemperatureF = 58, Min_TemperatureF = 52, | |
Max_Wind_SpeedMPH = NA, Mean_Wind_SpeedMPH = NA, | |
PrecipitationIn = 0, year = 2016)) ## predicted temp... | |
arrange(dat_climate_df, desc(Mean_TemperatureF)) | |
dat_climate_df_long = gather(dat_climate_df, "envi", "value", | |
Max_TemperatureF:PrecipitationIn) | |
dat_2016 = data.frame(x = t(dat_climate_df[69, 2:4]), | |
envi = c("Max_TemperatureF", "Mean_TemperatureF", | |
"Min_TemperatureF")) | |
filter(dat_climate_df_long, envi %in% c("Max_TemperatureF", "Mean_TemperatureF", | |
"Min_TemperatureF")) %>% | |
mutate(y2016 = year == 2016) %>% | |
ggplot(aes(x = year, y = value)) + | |
geom_point(aes(color = y2016, size = y2016 + 1)) + | |
# geom_smooth(method = "lm", alpha = 0.3) + | |
geom_hline(aes(yintercept = x), dat_2016) + | |
scale_x_continuous(breaks = seq(1950, 2015, 10)) + | |
facet_wrap(~envi, ncol = 3) + | |
scale_color_manual(values = viridis::viridis(6)[c(4,1)]) + | |
theme_bw(base_size = 20) + | |
theme(legend.position = "null") | |
ggsave("figs_4_slides/climate_0308.png", height = 4, width = 12) | |
filter(dat_climate_df_long, envi %in% c("Max_TemperatureF", "Mean_TemperatureF", | |
"Min_TemperatureF")) %>% | |
group_by(envi) %>% | |
do(broom::tidy(lm(value ~ seq_along(year), data = .))) | |
select(dat_climate_df, Date, contains("Temperature"))[, 2:4] %>% colMeans() | |
hist(dat_climate_df$Mean_TemperatureF) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment