co2_wide <- data.frame(matrix(co2, ncol = 12, byrow = TRUE)) |>
setNames(1:12) |>
mutate(year = 1959:1997) |>
pivot_longer(-year, names_to = "month", values_to = "co2") |>
mutate(month = as.numeric(month))Practicing joins activity with co2 data
Practice joins
These exercises are from Chapter 12, but with some modifications and clarifications.
Exercise 1
(This is from Exercise 3 in the text) You have previously seen the co2 data frame in readings and activities. The code below will create a tidy data frame that has 12 rows for each year (one for each month), and each row contains a single co2 value (rather than the original which has one row for each year containing 12 values).
- Note: this is the
co2dataset. Be sure that you are working withco2, because there is another dataset available in base R calledCO2.
We want to see if the monthly trend is changing. In order to do that, first we have to compute the year averages. Use the group_by and summarize to compute the average co2 for each year. Save this in an object called yearly_avg (yearly_avg should contain one row for each year, and two columns (the year and the co2 average)). Use head(10) on yearly_avg to see that your result seems correct when you render.
# Your code hereExercise 2
Now use the left_join function to add the yearly average to the co2_wide data set. Then add a column for the residual value. We compute the residual for each row with this subtraction: observed co2 measure - yearly average. Use head(15) to see that your result seems correct when you render.
# Your code here