sun, 25-jan-2015, 08:26

Following up on yesterday’s post about minimum temperatures, I was thinking that a cumulative measure of cold temperatures would probably be a better measure of how cold a winter is. We all remember the extremely cold days each winter when the propane gells or the car won’t start, but it’s the long periods of deep cold that really take their toll on buildings, equipment, and people in the Interior.

One way of measuring this is to find all the days in a winter year when the average temperature is below freezing and sum all the temperatures below freezing for that winter year. For example, if the temperature is 50°F, that’s not below freezing so it doesn’t count. If the temperature is −40°, that’s 72 freezing degrees (Fahrenheit). Do this for each day in a year and add up all the values.

Here’s the code to make the plot below (see my previous post for how we got fai_pivot).

fai_winter_year_freezing_degree_days <-
   fai_pivot %>%
      mutate(winter_year=year(dte - days(92)),
               fdd=ifelse(TAVG < 0, -1*TAVG*9/5, 0)) %>%
      filter(winter_year < 2014) %>%
      group_by(station_name, winter_year) %>%
      select(station_name, winter_year, fdd) %>%
      summarize(fdd=sum(fdd, na.rm=TRUE), n=n()) %>%
      filter(n>350) %>%
      select(station_name, winter_year, fdd) %>%
      spread(station_name, fdd)

fdd_gathered <-
   fai_winter_year_freezing_degree_days %>%
      gather(station_name, fdd, -winter_year) %>%
      arrange(winter_year)
q <-
   fdd_gathered %>%
      ggplot(aes(x=winter_year, y=fdd, colour=station_name)) +
            geom_point(size=1.5, position=position_jitter(w=0.5,h=0.0)) +
            geom_smooth(data=subset(fdd_gathered, winter_year<1975),
                        method="lm", se=FALSE) +
            geom_smooth(data=subset(fdd_gathered, winter_year>=1975),
                        method="lm", se=FALSE) +
            scale_x_continuous(name="Winter Year",
                               breaks=pretty_breaks(n=20)) +
            scale_y_continuous(name="Freezing degree days (degrees F)",
                               breaks=pretty_breaks(n=10)) +
            scale_color_manual(name="Station",
                              labels=c("College Observatory",
                                       "Fairbanks Airport",
                                       "University Exp. Station"),
                              values=c("darkorange", "blue", "darkcyan")) +
            theme_bw() +
            theme(legend.position = c(0.875, 0.120)) +
            theme(axis.text.x = element_text(angle=45, hjust=1))

rescale <- 0.65
svg('freezing_degree_days.svg', height=10*rescale, width=16*rescale)
print(q)
dev.off()

And the plot.

//media.swingleydev.com/img/blog/2015/01/freezing_degree_days.svg

Cumulative freezing degree days by winter year

You’ll notice I’ve split the trend lines at 1975. When I ran the regressions for the entire period, none of them were statistically significant, but looking at the plot, it seems like something happens in 1975 where the cumulative freezing degree days suddenly drop. Since then, they've been increasing at a faster, and statistically significant rate.

This is odd, and it makes me wonder if I've made a mistake in the calculations because what this says is that, at least since 1975, the winters are getting colder as measured by the total number of degrees below freezing each winter. My previous post (and studies of climate in general) show that the climate is warming, not cooling.

One bias that's possible with cumulative calculations like this is that missing data becomes more important, but I looked at the same relationships when I only include years with at least 364 days of valid data (only one or two missing days) and the same pattern exists.

Curious. When combined, this analysis and yesterday's suggest that winters in Fairbanks are getting colder overall, but that the minimum temperature in any year is likely to be warmer than in the past.

tags: R  weather  dplyr  climate  tidyr 
sat, 24-jan-2015, 12:41

The Weather Service is calling for our first −40° temperatures of the winter, which is pretty remarkable given how late in the winter it is. The 2014/2015 winter is turning out to be one of the warmest on record, and until this upcoming cold snap, we’ve only had a few days below normal, and mostly it’s been significantly warmer. You can see this on my Normalized temperature anomaly plot, where most of the last four months has been reddish.

I thought I’d take a look at the minimum winter temperatures for the three longest running Fairbanks weather stations to see what patterns emerge. This will be a good opportunity to further experiment with the dplyr and tidyr R packages I’m learning.

The data set is the Global Historical Climatology Network - Daily (GHCND) data from the National Climatic Data Center (NCDC). The data, at least as I’ve been collecting it, has been fully normalized, which is another way of saying that it’s stored in a way that makes database operations efficient, but not necessarily the way people want to look at it.

There are three main tables, ghchd_stations containing data about each station, ghcnd_variables containing information about the variables in the data, and ghcnd_obs which contains the observations. We need ghchd_stations in order to find what stations we’re interested in, by name or location, for example. And we need ghcnd_variables to convert the values in the observation table to the proper units. The observation table looks something like this:

gnchd_obs
station_id dte variable raw_value qual_flag
USW00026411 2014-12-25 TMIN -205  
USW00026411 2014-12-25 TMAX -77  
USW00026411 2014-12-25 PRCP 15  
USW00026411 2014-12-25 SNOW 20  
USW00026411 2014-12-25 SNWD 230  

There are a few problems with using this table directly. First, the station_id column doesn’t tell us anything about the station (name, location, etc.) without joining it to the stations table. Second, we need to use the variables table to convert the raw values listed in the table to their actual values. For example, temperatures are in degrees Celsius × 10, so we need to divide the raw value to get actual temperatures. Finally, to get the so that we have one row per date, with columns for the variables we’re interested in we have to “pivot” the data (to use Excel terminology).

Here’s how we get all the data using R.

Load the libraries we will need:

library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)
library(lubridate)
library(knitr)

Connect to the database and get the tables we need, choosing only the stations we want from the stations table. In the filter statement you can see we’re using a PostgreSQL specific operator ~ to do the filtering. In other databases we’d probably use %in% and include the station names as a list.

noaa_db <- src_postgres(host="localhost", user="cswingley", port=5434, dbname="noaa")

# Construct database table objects for the data
ghcnd_obs <- tbl(noaa_db, "ghcnd_obs")
ghcnd_vars <- tbl(noaa_db, "ghcnd_variables")

# Filter stations to just the long term Fairbanks stations:
fai_stations <-
   tbl(noaa_db, "ghcnd_stations") %>%
   filter(station_name %~% "(FAIRBANKS INT|UNIVERSITY EXP|COLLEGE OBSY)")

Here’s where we grab the data. We are using the magrittr package’s pipe operator (%>%) to chain operations together, making it really easy to follow exactly how we’re manipulating the data along the way.

# Get the raw data
fai_raw <-
   ghcnd_obs %>%
   inner_join(fai_stations, by="station_id") %>%
   inner_join(ghcnd_vars, by="variable") %>%
   mutate(value=raw_value*raw_multiplier) %>%
   filter(qual_flag=='') %>%
   select(station_name, dte, variable, value) %>%
   collect()

# Save it
save(fai_raw, file="fai_raw.rdata", compress="xz")

In order, we start with the complete observation table (which contains 29 million rows at this moment), then we join it with our filtered stations using inner_join(fai_stations, by="station_id"). Now we’re down to 723 thousand rows of data. We join it with the variables table, then create a new column called value that is the raw value from the observation table multiplied by the multiplier from the variable table. We remove any observation that doesn’t have an empty string for the quality flag (a value in this fields indicates there’s something wrong with the data). Finally, we reduce the number of columns we’re keeping to just the station name, date, variable name, and the actual value.

We then use collect() to actually run all these operations and collect the results into an R object. One of the neat things about database operations using dplyr is that the SQL isn’t actually performed until it is actually necessary, which really speeds up the testing phase of the analysis. You can play around with joining, filtering and transforming the data using operations that are fast until you have it just right, then collect() to finalize the steps.

At this stage, the data is still in it’s normalized form. We’ve fixed the station name and the values in the data are now what was observed, but we still need to pivot the data to make is useful.

We’ll use the tidyr spread() function to make the value that appears in the variable column (TMIN, TMAX, etc.) appear as columns in the output, and put the data in the value column into the cells in each column and row. We’re also calculating an average daily temperature from the minimum and maximum temperatures and selecting just the columns we want.

# pivot, calculate average temp, include useful vars
fai_pivot <-
   fai_raw %>%
   spread(variable, value) %>%
   transform(TAVG=(TMIN+TMAX)/2.0) %>%
   select(station_name, dte, TAVG, TMIN, TMAX, TOBS, PRCP, SNOW, SNWD,
         WSF1, WDF1, WSF2, WDF2, WSF5, WDF5, WSFG, WDFG, TSUN)

Now we’ve got a table with rows for each station name and date, and columns with all the observed variables we might be interested in.

Time for some analysis. Let’s get the minimum temperatures by year and station. When looking at winter temperatures, it makes more sense to group by “winter year” rather that the actual year. In our case, we’re subtracting 92 days from the date and getting the year. This makes the winter year start in April instead of January and means that the 2014/2015 winter has a winter year of 2014.

# Find coldest temperatures by winter year, as a nice table
fai_winter_year_minimum <-
   fai_pivot %>%
      mutate(winter_year=year(dte - days(92))) %>%
      filter(winter_year < 2014) %>%
      group_by(station_name, winter_year) %>%
      select(station_name, winter_year, TMIN) %>%
      summarize(tmin=min(TMIN*9/5+32, na.rm=TRUE), n=n()) %>%
      filter(n>350) %>%
      select(station_name, winter_year, tmin) %>%
      spread(station_name, tmin)

In order, we’re taking the pivoted data (fai_pivot), adding a column for winter year (mutate), removing the data from the current year since the winter isn’t over (filter), grouping by station and winter year (group_by), reducing the columns down to just minimum temperature (select), summarizing by minimum temperature after converting to Fahrenheit and the number of days with valid data (summarize), only selecting years with 350 ore more days of data (select), and finally grabbing and formatting just the columns we want (select, spread).

Here’s the last 20 years and how we get a nice table of them.

last_twenty <-
   fai_winter_year_minimum %>%
      filter(winter_year > 1993)

# Write to an RST table
sink("last_twenty.rst")
print(kable(last_twenty, format="rst"))
sink()
Minimum temperatures, last 20 years
Winter Year College Obsy Fairbanks Airport University Exp Stn
1994 -43.96 -47.92 -47.92
1995 -45.04 -45.04 -47.92
1996 -50.98 -50.98 -54.04
1997 -43.96 -47.92 -47.92
1998 -52.06 -54.94 -54.04
1999 -50.08 -52.96 -50.98
2000 -27.94 -36.04 -27.04
2001 -40.00 -43.06 -36.04
2002 -34.96 -38.92 -34.06
2003 -45.94 -45.94 NA
2004 NA -47.02 -49.00
2005 -47.92 -50.98 -49.00
2006 NA -43.96 -41.98
2007 -38.92 -47.92 -45.94
2008 -47.02 -47.02 -49.00
2009 -32.98 -41.08 -41.08
2010 -36.94 -43.96 -38.02
2011 -47.92 -50.98 -52.06
2012 -43.96 -47.92 -45.04
2013 -36.94 -40.90 NA

To plot it, we need to re-normalize it so that each row in the data has winter_year, station_name, and tmin in it.

Here’s the plotting code, including the commands to re-normalize.

q <-
   fai_winter_year_minimum %>%
      gather(station_name, tmin, -winter_year) %>%
      arrange(winter_year) %>%
      ggplot(aes(x=winter_year, y=tmin, colour=station_name)) +
            geom_point(size=1.5, position=position_jitter(w=0.5,h=0.0)) +
            geom_smooth(method="lm", se=FALSE) +
            scale_x_continuous(name="Winter Year",
                               breaks=pretty_breaks(n=20)) +
            scale_y_continuous(name="Minimum temperature (degrees F)",
                               breaks=pretty_breaks(n=10)) +
            scale_color_manual(name="Station",
                              labels=c("College Observatory",
                                       "Fairbanks Airport",
                                       "University Exp. Station"),
                              values=c("darkorange", "blue", "darkcyan")) +
            theme_bw() +
            theme(legend.position = c(0.875, 0.120)) +
            theme(axis.text.x = element_text(angle=45, hjust=1))

The lines are the linear regression lines between winter year and minimum temperature. You can see that the trend is for increasing minimum temperatures. Each of these lines is statistically significant (both the coefficients and the overall model), but they only explain about 7% of the variation in temperatures. Given the spread of the points, that’s not surprising. The data shows that the lowest winter temperature at the Fairbanks airport is rising by 0.062 degrees each year.

tags: R  weather  dplyr  climate  tidyr 
sun, 11-jan-2015, 10:34

I spent some time this weekend playing with a couple interesting new R packages that should help with some of the difficulty manipulating data with the base packages. Getting data into a format appropriate for plotting or running statistical models often seems to take more time than anything else, and the process can be very frustrating because of seemingly non-sensical error messages from R.

R guru Hadley Wickham has written some of the best packages for data manipulation (reshape2, plyr) and plotting (ggplot2). He’s got a new pair of packages (tidyr and dplyr) and a theory of getting data into the proper format (http://vita.had.co.nz/papers/tidy-data.pdf) that look very promising.

A couple other tools I wanted to look at include a new way of piping data from one operation to another (magrittr), which is a basic part of the Unix philosophy of having many tools that do one thing well and stringing them together to do neat things, and an interactive graphic package, ggvis, that should be really good for data investigation.

For this investigation, I’m looking at the names of our dogs, past and present, and how popular they are as people names in the United States. This data comes from the Social Security Administration and is available in the R package babynames.

install.packages("babynames")
library(babynames)
head(babynames)
Source: local data frame [6 x 5]

year sex      name    n       prop
1 1880   F      Mary 7065 0.07238359
2 1880   F      Anna 2604 0.02667896
3 1880   F      Emma 2003 0.02052149
4 1880   F Elizabeth 1939 0.01986579
5 1880   F    Minnie 1746 0.01788843
6 1880   F  Margaret 1578 0.01616720

The data has the number of registrations (n) and proportion of total registrations (prop) for each year from 1880 through 2013 for all name and sex combinations.

What I want to see is how popular out dog names are. All of our dogs have been adopted, but some we chose names for them (Nika, Piper, Kiva), and the rest came with names we didn’t change (Deuce, Buddy, Koidern, Lennier, Martin, Monte and the second Piper). Dog mushers often choose a theme for a litter of puppies, which accounts for some of the unusual names (Deuce came from a litter of classic cars, Lennier came from a litter of Babylon 5 character names, Koidern from a litter of Yukon River tributary names).

So what I want to do is subset the babynames database to just the names of our dogs, combine male and female names together, and plot the popularity of these names over time.

Here’s how that’s done using the magrittr pipe operator (%>%):

library(dplyr)
library(magrittr)

dog_names <- babynames %>%
   filter(name %in% c("Nika", "Piper", "Buddy", "Koidern", "Deuce",
                     "Kiva", "Lennier", "Martin", "Monte")) %>%
   group_by(year, name) %>%
   summarise(prop=sum(prop)) %>%
   transform(name=factor(name)) %>%
   ungroup() %>%
   arrange(name, year)

We are assigning the result of all the pipes to dog_names. In order, we take the babynames data set and filter it by our dog’s names. Then we group by year and name, and summarize the proportion values by sum. At this point we have data with just our dog’s names, with the proportions of both male and female baby names combined. Next, we convert the name variable to a factor, remove the grouping, and sort by name and year.

Here’s what it looks like now:

> head(dog_names)
year  name         prop
1 1893 Buddy 4.130866e-05
2 1894 Buddy 5.604573e-05
3 1896 Buddy 8.522045e-05
4 1898 Buddy 3.784782e-05
5 1899 Buddy 4.340353e-05
6 1900 Buddy 6.167015e-05

Now we’ve got tidy filtered and sorted data, so let’s plot it. I’ve been using ggplot2 for many years, and I think it’s the best way to produce publication quality figures. But usually you want to do some investigation of the data before doing that, and doing this in ggplot2 involves many cycles of code manipulation, plotting, viewing in order to see what you’ve got and how you want the final version to look.

ggvis is a new package that displays data interactively in a web browser. It also supports the pipe operator, so you can pipe the data directly into the plotting routine. It’s somewhat similar to ggplot2, but has some new conventions that are required in order to handle interactivity. Here’s a plot of my dog names data. The first part is the same as before, but I’m piping the result directly into ggivs.

library(ggvis)
babynames %>%
   filter(name %in% c("Nika", "Piper", "Buddy", "Koidern", "Deuce",
                     "Kiva", "Lennier", "Martin", "Monte")) %>%
   group_by(year, name) %>%
   summarise(prop=sum(prop)) %>%
   transform(name=factor(name)) %>%
   ungroup() %>%
   arrange(name, year) %>%
   ggvis(~year, ~prop, stroke=~name, fill=~name) %>%
   # layer_lines(strokeWidth:=2) %>%
   layer_points(size:=15) %>%
   add_axis("x", title="Year", format="####") %>%
   add_axis("y", title="Proportion of total names", title_offset=50) %>%
   add_legend(c("stroke", "fill"), title="Name")
ggvis version

Popularity of our dog names, ggvis version

Typically, I prefer to include lines and points in a timeseries plot like this, but I couldn't get ggvis to color the lines and the points without some very strange fill artifacts.

Here’s what I’d consider to be a high quality version of this, generated with ggplot:

library(ggplot2)
library(scales)

q <- ggplot(data=dog_names, aes(x=year, y=prop, colour=name)) +
         geom_point(size=1.75) +
         geom_line() +
         theme_bw() +
         scale_colour_brewer(palette="Set1") +
         scale_x_continuous(name="Year", breaks=pretty_breaks(n=10)) +
         scale_y_continuous(name="Proportion of total names", breaks=pretty_breaks(n=10))
rescale <- 0.50
svg("dog_names_ggplot2.svg", height=9*rescale, width=16*rescale)
print(q)
dev.off()
ggplo2 version

Popularity of our dog names, ggplot2 version

I think the two plots are pretty similar, and I’m impressed with how good the ggvis plot looks and how similar the language is to ggplot2. And I really like the pipe operator compared with a long list of individual statements or the way you add things together with ggplot2.

Both plots suffer from having too many groups (seven), which means it becomes difficult to interpret the colors on the plot. Choosing a good palette is key to this, and is one of those parts of figure production that can really take a long time. I don’t think my choices in the ggplot2 version is optimal, but I got tired of looking. The other problem is the collection of dog names with very low proportions among human babies. Because they’re all overlapping near the axis, this data is obscured. Both problems could be solved by stacking two plots on top of each other, one with the more popular names (Martin, Piper, Buddy and Monte) and one with the less popular ones (Deuce, Kiva, Nika) using different scales for the proportion axis.

What does the plot show? Among our dog’s names, Martin was the most popular, but it’s popularity has been declining since the 60s, and the name Piper has been increasing since 2000. Both Monte and Buddy were popular in the past, but have declined to low levels recently.

For reference, here are the number of babies in 2013 that were given names matching those of our dogs:

babynames %>%
   filter(name %in% c("Nika", "Piper", "Buddy", "Koidern", "Deuce",
                     "Kiva", "Lennier", "Martin", "Monte")
         & year==2013) %>%
   group_by(year, name) %>%
   summarise(n=sum(n)) %>%
   transform(name=factor(name)) %>%
   ungroup() %>%
   arrange(desc(n))

year   name    n
1 2013  Piper 3166
2 2013 Martin 1330
3 2013  Monte   81
4 2013   Nika   67
5 2013  Buddy   21
6 2013   Kiva   18
7 2013  Deuce    5
tags: dogs  R  ggplot2  names  dplyr  magrittr  ggvis 
Meta Photolog Archives