Practicing pivots activity 2



These exercises are from Chapter 11, but with some modifications and clarifications.

Exercise 1

This command will define the co2_wide object:

co2_wide <- data.frame(matrix(co2, ncol = 12, byrow = TRUE)) |> 
  setNames(1:12) |>
  mutate(year = as.character(1959:1997))

Now write an instruction that uses the pivot_longer function to wrangle this into a tidy dataset. Use the name co2 for the column that will have the CO2 measurements, and use the name month for the column that will hold the month values. Save the resulting dataframe in co2_tidy.

Your goal is a data frame that has 12 rows for each year, and 3 columns, one for the year, one for the month, one for the co2 value.

# Your code here

Exercise 2

Look at the code in the next chunk. You probably expect it to generate a plot that has a different curve for each year of data. After studying the code, adjust the eval option so that the code executes when you render. What do you see?

co2_tidy |> 
  ggplot(aes(month, co2, color = year)) + geom_line()

You didn’t get what you expected, did you? Now you can run glimpse() on the data frame and you’ll see that the month field is actually character data.
But we need it to be numeric for the plot to work correctly. (If you add the glimpse() command to your QMD document, be sure to remove it when you are done.)

In the chunk below, rewrite the above code with modifications so that first you make the month column numeric, then generate the plot.

# revised code goes here