Currently it only fills "new" missing values. spread() filled both new and pre-existing missing values.
If it also filled existing missing values, that would help with the complete() + pivot_wider() story
library(tidyverse)
d <- head(mtcars) %>%
group_by(gear, cyl) %>%
summarise(mean_hp = mean(hp)) %>%
ungroup()
#> `summarise()` has grouped output by 'gear'. You can override using the `.groups` argument.
d
#> # A tibble: 4 × 3
#> gear cyl mean_hp
#> <dbl> <dbl> <dbl>
#> 1 3 6 108.
#> 2 3 8 175
#> 3 4 4 93
#> 4 4 6 110
pivot_wider(d, names_from = cyl, values_from = mean_hp, values_fill = 0)
#> # A tibble: 2 × 4
#> gear `6` `8` `4`
#> <dbl> <dbl> <dbl> <dbl>
#> 1 3 108. 175 0
#> 2 4 110 0 93
spread(d, cyl, mean_hp, fill = 0)
#> # A tibble: 2 × 4
#> gear `4` `6` `8`
#> <dbl> <dbl> <dbl> <dbl>
#> 1 3 0 108. 175
#> 2 4 93 110 0
# but maybe we want gear and cyl in numeric ordering
d <- complete(d, gear, cyl)
d
#> # A tibble: 6 × 3
#> gear cyl mean_hp
#> <dbl> <dbl> <dbl>
#> 1 3 4 NA
#> 2 3 6 108.
#> 3 3 8 175
#> 4 4 4 93
#> 5 4 6 110
#> 6 4 8 NA
# it won't fill existing NAs
pivot_wider(d, names_from = cyl, values_from = mean_hp, values_fill = 0)
#> # A tibble: 2 × 4
#> gear `4` `6` `8`
#> <dbl> <dbl> <dbl> <dbl>
#> 1 3 NA 108. 175
#> 2 4 93 110 NA
spread(d, cyl, mean_hp, fill = 0)
#> # A tibble: 2 × 4
#> gear `4` `6` `8`
#> <dbl> <dbl> <dbl> <dbl>
#> 1 3 0 108. 175
#> 2 4 93 110 0
Created on 2021-12-14 by the reprex package (v2.0.1)
Currently it only fills "new" missing values.
spread()filled both new and pre-existing missing values.If it also filled existing missing values, that would help with the
complete() + pivot_wider()storyCreated on 2021-12-14 by the reprex package (v2.0.1)