Jrm_FRL
Jrm_FRL

Reputation: 1423

Cannot fill missing values with new pivot_wider() from tidyr

I am getting crazy with the new tidyr::pivot_wider() function with the missing values feature. It works sometimes, sometimes not.

Here is a reproducible example:

require('tidyr')
df <- data.frame(
  color = c("green", "yellow"),
  nb = c(1758, 12)
  )

# add one level
df$color <- factor(df$color, levels = c("green", "yellow", "red"))

This works well:

# with deprecated `spread`
spread(data = df, 
       key = color, value = nb, 
       fill = 0,
       drop = F)
>>  green yellow red  
>>1  1758     12   0

But this does not

# with new `pivot_wider`
pivot_wider(data = df, 
            names_from = color, 
            values_from = nb, 
            values_fill = list(nb = 0))
# A tibble: 1 x 2
  green yellow
  <dbl>  <dbl>
1  1758     12

What am I doing wrong ?

I have noted this partial answer but I would like to get an equivalent behaviour of my function, not having to add an intermediate step.

Upvotes: 3

Views: 1645

Answers (1)

akrun
akrun

Reputation: 887771

We can use complete to create the combination bassed on the levels and then use pivot_wider

library(dplyr)
library(tidyr)
df %>% 
  complete(color = levels(color), fill = list(nb = 0)) %>% 
  pivot_wider(names_from = color, values_from = nb)
# A tibble: 1 x 3
#  green   red yellow
#  <dbl> <dbl>  <dbl>
#1  1758     0     12

Upvotes: 2

Related Questions