/labs/data-reshaping-lab-key.R

https://github.com/SISBID/Module1 · R · 55 lines · 28 code · 17 blank · 10 comment · 0 complexity · 699e483025f90829a805d537b240a0c1 MD5 · raw file

  1. ## ----setup, include=FALSE-----------------------------------------------------
  2. knitr::opts_chunk$set(echo = TRUE)
  3. ## -----------------------------------------------------------------------------
  4. library(tidyverse)
  5. ## ---- message = FALSE---------------------------------------------------------
  6. wide = read_csv(
  7. "http://sisbid.github.io/Data-Wrangling/data/Charm_City_Circulator_Ridership.csv"
  8. )
  9. ## -----------------------------------------------------------------------------
  10. long = wide %>%
  11. pivot_longer( !c(daily, day, date), names_to = "variable", values_to = "n_people")
  12. head(long)
  13. ## -----------------------------------------------------------------------------
  14. # We over-wrote the day column by assigning it new values (in this case, calendar "day")
  15. long2 = long %>%
  16. separate(col = "date", into = c("month", "day", "year"),
  17. sep = "/", remove = FALSE)
  18. table(long2$day)
  19. ## -----------------------------------------------------------------------------
  20. long2 = long2 %>%
  21. unite(col = "newdate", year, month, day, sep = "-")
  22. head(long2)
  23. ## ---- error = TRUE------------------------------------------------------------
  24. long = long %>%
  25. mutate(
  26. variable = variable %>%
  27. str_replace("Board", "_Board") %>%
  28. str_replace("Alight", "_Alight") %>%
  29. str_replace("Average", "_Average")
  30. )
  31. head(long)
  32. ## -----------------------------------------------------------------------------
  33. long = long %>%
  34. separate(col = "variable", into = c("route", "type"), sep = "_")
  35. head(long)
  36. ## -----------------------------------------------------------------------------
  37. wide_by_route = long %>%
  38. pivot_wider(names_from = route, values_from = n_people)