# load packages ----
library(tidyverse)
library(palmerpenguins)
Setup
Tidy Data Review
Example untidy / wide data:
# create some untidy temperature data ----
<- tribble(
temp_data_wide ~date, ~station1, ~station2, ~station3,
"2023-10-01", 30.1, 29.8, 31.2,
"2023-11-01", 28.6, 29.1, 33.4,
"2023-12-01", 29.9, 28.5, 32.3
)
# print it out ----
print(temp_data_wide)
# A tibble: 3 × 4
date station1 station2 station3
<chr> <dbl> <dbl> <dbl>
1 2023-10-01 30.1 29.8 31.2
2 2023-11-01 28.6 29.1 33.4
3 2023-12-01 29.9 28.5 32.3
Using pivot_longer()
to “lengthen” / tidy our data:
# convert data from wide > long ----
<- temp_data_wide %>%
temp_data_long pivot_longer(cols = starts_with("station"),
names_to = "station_id",
values_to = "temp_c")
# print it out ----
print(temp_data_long)
# A tibble: 9 × 3
date station_id temp_c
<chr> <chr> <dbl>
1 2023-10-01 station1 30.1
2 2023-10-01 station2 29.8
3 2023-10-01 station3 31.2
4 2023-11-01 station1 28.6
5 2023-11-01 station2 29.1
6 2023-11-01 station3 33.4
7 2023-12-01 station1 29.9
8 2023-12-01 station2 28.5
9 2023-12-01 station3 32.3