Tidy Data

Pivoting

long to wide form

table4a_long <- table4a %>%
    
    pivot_longer(cols = c(`1999`, `2000`),
                 names_to = "year",
                 values_to = "cases")

wide to long form

table4a_long %>%
    
    pivot_wider(names_from = year,
                values_from = cases)
## # A tibble: 3 × 3
##   country     `1999` `2000`
##   <chr>        <dbl>  <dbl>
## 1 Afghanistan    745   2666
## 2 Brazil       37737  80488
## 3 China       212258 213766

Seperating and Uniting

seperate a column

table3_sep <- table3 %>%
    
    separate(col = rate, into = c("cases", "population"))

unite two columns

#table3_sep %>%
    
    #unite(col = "rate", c(case:population), sep = "/")

Missing Values

bikes <- tibble(
  bike_model  = c("A", "A", "B", "B", "C"),
  material    = c("steel", "aluminium", "steel", "aluminium", "steel"),
  price = c(100, 200, 300, 400, 500)
)
bikes %>%
    
    pivot_wider(names_from = bike_model, values_from = price)
## # A tibble: 2 × 4
##   material      A     B     C
##   <chr>     <dbl> <dbl> <dbl>
## 1 steel       100   300   500
## 2 aluminium   200   400    NA
bikes %>%
    
    complete(bike_model, material)
## # A tibble: 6 × 3
##   bike_model material  price
##   <chr>      <chr>     <dbl>
## 1 A          aluminium   200
## 2 A          steel       100
## 3 B          aluminium   400
## 4 B          steel       300
## 5 C          aluminium    NA
## 6 C          steel       500
treatment <- tribble(
  ~ person,           ~ treatment, ~response,
  "Derrick Whitmore", 1,           7,
  NA,                 2,           10,
  NA,                 3,           9,
  "Katherine Burke",  1,           4
)

treatment %>%
    
    fill(person, .direction = "up")
## # A tibble: 4 × 3
##   person           treatment response
##   <chr>                <dbl>    <dbl>
## 1 Derrick Whitmore         1        7
## 2 Katherine Burke          2       10
## 3 Katherine Burke          3        9
## 4 Katherine Burke          1        4

Nontidy Data