Missing Values
stocks <- tibble(
year = c(2015, 2015, 2015, 2015, 2016, 2016, 2016),
qtr = c( 1, 2, 3, 4, 2, 3, 4),
return = c(1.88, 0.59, 0.35, NA, 0.92, 0.17, 2.66)
)
stocks %>%
pivot_wider(names_from = year, values_from = return)
## # A tibble: 4 × 3
## qtr `2015` `2016`
## <dbl> <dbl> <dbl>
## 1 1 1.88 NA
## 2 2 0.59 0.92
## 3 3 0.35 0.17
## 4 4 NA 2.66
bikes <- tibble(
bike_model = c("A", "A", "B", "B", "C"),
material = c("steel", "aluminum", "steel", "aluminim", "steel"),
price = c(100, 200, 300, 400, 500)
)
bikes %>%
pivot_wider(names_from = bike_model, values_from = price)
## # A tibble: 3 × 4
## material A B C
## <chr> <dbl> <dbl> <dbl>
## 1 steel 100 300 500
## 2 aluminum 200 NA NA
## 3 aluminim NA 400 NA
bikes %>%
complete(bike_model, material)
## # A tibble: 9 × 3
## bike_model material price
## <chr> <chr> <dbl>
## 1 A aluminim NA
## 2 A aluminum 200
## 3 A steel 100
## 4 B aluminim 400
## 5 B aluminum NA
## 6 B steel 300
## 7 C aluminim NA
## 8 C aluminum NA
## 9 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