Session 4: Homework 2
Climate change and temperature anomalies
If we wanted to study climate change, we can find data on the Combined Land-Surface Air and Sea-Surface Water Temperature Anomalies in the Northern Hemisphere at NASA’s Goddard Institute for Space Studies. The tabular data of temperature anomalies can be found here
To define temperature anomalies you need to have a reference, or base, period which NASA clearly states that it is the period between 1951-1980.
Run the code below to load the file:
weather <-
read_csv("https://data.giss.nasa.gov/gistemp/tabledata_v4/NH.Ts+dSST.csv",
skip = 1,
na = "***")
Notice that, when using this function, we added two options: skip and
na.
- The
skip=1option is there as the real data table only starts in Row 2, so we need to skip one row. na = "***"option informs R how missing observations in the spreadsheet are coded. When looking at the spreadsheet, you can see that missing data is coded as “***”. It is best to specify this here, as otherwise some of the data is not recognized as numeric data.
Once the data is loaded, notice that there is a object titled weather
in the Environment panel. If you cannot see the panel (usually on the
top-right), go to Tools > Global Options > Pane Layout and tick
the checkbox next to Environment. Click on the weather object, and
the dataframe will pop up on a seperate tab. Inspect the dataframe.
For each month and year, the dataframe shows the deviation of temperature from the normal (expected). Further the dataframe is in wide format.
You have two objectives in this section:
Select the year and the twelve month variables from the
weatherdataset. We do not need the others (J-D, D-N, DJF, etc.) for this assignment. Hint: useselect()function.Convert the dataframe from wide to ‘long’ format. Hint: use
gather()orpivot_longer()function. Name the new dataframe astidyweather, name the variable containing the name of the month asmonth, and the temperature deviation values asdelta.
Inspect your dataframe. It should have three variables now, one each for
- year,
- month, and
- delta, or temperature deviation.
Plotting Information
Let us plot the data using a time-series scatter plot, and add a
trendline. To do that, we first need to create a new variable called
date in order to ensure that the delta values are plot
chronologically.
In the following chunk of code, I used the
eval=FALSEargument, which does not run a chunk of code; I did so that you can knit the document before tidying the data and creating a new dataframetidyweather. When you actually want to run this code and knit your document, you must deleteeval=FALSE, not just here but in all chunks wereeval=FALSEappears.
tidyweather <- tidyweather %>%
mutate(date = ymd(paste(as.character(Year), Month, "1")),
month = month(date, label=TRUE),
year = year(date))
ggplot(tidyweather, aes(x=date, y = delta))+
geom_point()+
geom_smooth(color="red") +
theme_bw() +
labs (
title = "Weather Anomalies"
)
Is the effect of increasing temperature more pronounced in some months?
Use facet_wrap() to produce a seperate scatter plot for each month,
again with a smoothing line. Your chart should human-readable labels;
that is, each month should be labeled “Jan”, “Feb”, “Mar” (full or
abbreviated month names are fine), not 1, 2, 3.
It is sometimes useful to group data into different time periods to
study historical data. For example, we often refer to decades such as
1970s, 1980s, 1990s etc. to refer to a period of time. NASA calcuialtes
a temperature anomaly, as difference form the base periof of 1951-1980.
The code below creates a new data frame called comparison that groups
data in five time periods: 1881-1920, 1921-1950, 1951-1980, 1981-2010
and 2011-present.
We remove data before 1800 and before using filter. Then, we use the
mutate function to create a new variable interval which contains
information on which period each observation belongs to. We can assign
the different periods using case_when().
comparison <- tidyweather %>%
filter(Year>= 1881) %>% #remove years prior to 1881
#create new variable 'interval', and assign values based on criteria below:
mutate(interval = case_when(
Year %in% c(1881:1920) ~ "1881-1920",
Year %in% c(1921:1950) ~ "1921-1950",
Year %in% c(1951:1980) ~ "1951-1980",
Year %in% c(1981:2010) ~ "1981-2010",
TRUE ~ "2011-present"
))
Inspect the comparison dataframe by clicking on it in the
Environment pane.
Now that we have the interval variable, we can create a density plot
to study the distribution of monthly deviations (delta), grouped by
the different time periods we are interested in. Set fill to
interval to group and colour the data by different time periods.
So far, we have been working with monthly anomalies. However, we might
be interested in average annual anomalies. We can do this by using
group_by() and summarise(), followed by a scatter plot to display
the result.
#creating yearly averages
average_annual_anomaly <- tidyweather %>%
group_by(Year) %>% #grouping data by Year
# creating summaries for mean delta
# use `na.rm=TRUE` to eliminate NA (not available) values
summarise(......)
#plotting the data:
#Fit the best fit line, using LOESS method
#change theme to theme_bw() to have white background + black frame around plot
Confidence Interval for delta
NASA points out on their website that
A one-degree global change is significant because it takes a vast amount of heat to warm all the oceans, atmosphere, and land by that much. In the past, a one- to two-degree drop was all it took to plunge the Earth into the Little Ice Age.
Your task is to construct a confidence interval for the average annual
delta since 2011, both using a formula and using a bootstrap simulation
with the infer package. Recall that the dataframe comparison has
already grouped temperature anomalies according to time intervals; we
are only interested in what is happening between 2011-present.
formula_ci <- comparison %>%
# choose the interval 2011-present
# what dplyr verb will you use?
# calculate summary statistics for temperature deviation (delta)
# calculate mean, SD, count, SE, lower/upper 95% CI
# what dplyr verb will you use?
#print out formula_CI
formula_ci
What is the data showing us? Please type your answer after (and outside!) this blockquote. You have to explain what you have done, and the interpretation of the result. One paragraph max, please!
Biden’s Approval Margins
As we saw in class, fivethirtyeight.com has detailed data on all polls that track the president’s approval
# Import approval polls data directly off fivethirtyeight website
approval_polllist <- read_csv('https://projects.fivethirtyeight.com/biden-approval-data/approval_polllist.csv')
glimpse(approval_polllist)
## Rows: 4,572
## Columns: 22
## $ president <chr> "Joe Biden", "Joe Biden", "Joe Biden", "Joe Biden"…
## $ subgroup <chr> "All polls", "All polls", "All polls", "All polls"…
## $ modeldate <chr> "9/19/2022", "9/19/2022", "9/19/2022", "9/19/2022"…
## $ startdate <chr> "1/19/2021", "1/19/2021", "1/20/2021", "1/20/2021"…
## $ enddate <chr> "1/21/2021", "1/21/2021", "1/21/2021", "1/21/2021"…
## $ pollster <chr> "Morning Consult", "Rasmussen Reports/Pulse Opinio…
## $ grade <chr> "B", "B", "B-", "B", "B", "B+", "B+", "B", "B-", "…
## $ samplesize <dbl> 15000, 1500, 1115, 1993, 15000, 1516, 941, 15000, …
## $ population <chr> "a", "lv", "a", "rv", "a", "a", "rv", "a", "rv", "…
## $ weight <dbl> 0.2594, 0.3382, 1.1014, 0.0930, 0.2333, 1.2454, 1.…
## $ influence <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,…
## $ approve <dbl> 50.0, 48.0, 55.5, 56.0, 51.0, 45.0, 63.0, 52.0, 58…
## $ disapprove <dbl> 28.0, 45.0, 31.6, 31.0, 28.0, 28.0, 37.0, 29.0, 32…
## $ adjusted_approve <dbl> 49.4, 49.1, 54.6, 55.4, 50.4, 46.0, 59.4, 51.4, 57…
## $ adjusted_disapprove <dbl> 30.9, 40.3, 32.4, 33.9, 30.9, 29.0, 38.4, 31.9, 32…
## $ multiversions <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
## $ tracking <lgl> TRUE, TRUE, NA, NA, TRUE, NA, NA, TRUE, NA, TRUE, …
## $ url <chr> "https://morningconsult.com/form/global-leader-app…
## $ poll_id <dbl> 74272, 74247, 74248, 74246, 74273, 74327, 74256, 7…
## $ question_id <dbl> 139491, 139395, 139404, 139394, 139492, 139570, 13…
## $ createddate <chr> "1/28/2021", "1/22/2021", "1/22/2021", "1/22/2021"…
## $ timestamp <chr> "09:58:31 19 Sep 2022", "09:58:31 19 Sep 2022", "0…
# Use `lubridate` to fix dates, as they are given as characters.
Create a plot
What I would like you to do is to calculate the average net approval
rate (approve- disapprove) for each week since he got into office. I
want you plot the net approval for each week in 2022, along with its 95%
confidence interval. There are various dates given for each poll, please
use enddate, i.e., the date the poll ended. Your plot should look
something like this:

Challenge 1: Excess rentals in TfL bike sharing
Recall the TfL data on how many bikes were hired every single day. We can get the latest data by running the following
url <- "https://data.london.gov.uk/download/number-bicycle-hires/ac29363e-e0cb-47cc-a97a-e216d900a6b0/tfl-daily-cycle-hires.xlsx"
# Download TFL data to temporary file
httr::GET(url, write_disk(bike.temp <- tempfile(fileext = ".xlsx")))
## Response [https://airdrive-secure.s3-eu-west-1.amazonaws.com/london/dataset/number-bicycle-hires/2022-09-06T12%3A41%3A48/tfl-daily-cycle-hires.xlsx?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJJDIMAIVZJDICKHA%2F20220914%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20220914T172310Z&X-Amz-Expires=300&X-Amz-Signature=47301b6afb6e588a511e0c99a014caaa54985015958ef06b54cf1812e8ad9916&X-Amz-SignedHeaders=host]
## Date: 2022-09-14 17:23
## Status: 200
## Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
## Size: 180 kB
## <ON DISK> /var/folders/rl/nrz17jqj7nncc2gtb00vqxlh0000gn/T//Rtmpf3M6Pq/file78252852c6e7.xlsx
# Use read_excel to read it as dataframe
bike0 <- read_excel(bike.temp,
sheet = "Data",
range = cell_cols("A:B"))
# change dates to get year, month, and week
bike <- bike0 %>%
clean_names() %>%
rename (bikes_hired = number_of_bicycle_hires) %>%
mutate (year = year(day),
month = lubridate::month(day, label = TRUE),
week = isoweek(day))
We can easily create a facet grid that plots bikes hired by month and year since 2015

However, the challenge I want you to work on is to reproduce the following two graphs.

The second one looks at percentage changes from the expected level of weekly rentals. The two grey shaded rectangles correspond to Q2 (weeks 14-26) and Q4 (weeks 40-52).

For both of these graphs, you have to calculate the expected number of
rentals per week or month between 2016-2019 and then, see how each
week/month of 2020-2022 compares to the expected rentals. Think of the
calculation excess_rentals = actual_rentals - expected_rentals.
Should you use the mean or the median to calculate your expected rentals? Why?
In creating your plots, you may find these links useful:
Deliverables
As usual, there is a lot of explanatory text, comments, etc. You do not need these, so delete them and produce a stand-alone document that you could share with someone. Knit the edited and completed R Markdown file as an HTML document (use the “Knit” button at the top of the script editor window) and upload it to Canvas.
Details
- Who did you collaborate with: TYPE NAMES HERE
- Approximately how much time did you spend on this problem set: ANSWER HERE
- What, if anything, gave you the most trouble: ANSWER HERE
Please seek out help when you need it, and remember the 15-minute rule. You know enough R (and have enough examples of code from class and your readings) to be able to do this. If you get stuck, ask for help from others, post a question on Slack– and remember that I am here to help too!
As a true test to yourself, do you understand the code you submitted and are you able to explain it to someone else?
Rubric
Check minus (1/5): Displays minimal effort. Doesn’t complete all components. Code is poorly written and not documented. Uses the same type of plot for each graph, or doesn’t use plots appropriate for the variables being analyzed.
Check (3/5): Solid effort. Hits all the elements. No clear mistakes. Easy to follow (both the code and the output).
Check plus (5/5): Finished all components of the assignment correctly and addressed both challenges. Code is well-documented (both self-documented and with additional comments as necessary). Used tidyverse, instead of base R. Graphs and tables are properly labelled. Analysis is clear and easy to follow, either because graphs are labeled clearly or you’ve written additional text to describe how you interpret the output.
Second, you can produce an animation to explore the relationship between CO2 per capita emissions and the deployment of renewables. As the % of energy generated by renewables goes up, do CO2 per capita emissions seem to go down?