Thank you very much for the reply. It definitely solves the problem using values_fill. But, I was trying to understand how values_fn works and later use it for other purpose.
library(tidyverse)
dx<-data.frame(A = c(1,2,2,4,5),B = c("B1","B3","B3","B1","B3"),C = c("C1","C4","C5","C8","C9"))
p1<-dx %>%
pivot_wider(
names_from = c(B),
values_from = c(C),
names_glue = "{B}_{.value}",
values_fn = list
)
map_dbl(p1$B1_C, length)
#> [1] 1 0 1 0
map_dbl(p1$B3_C, length)
#> [1] 0 2 0 1
When I try to use values_fn = length in pivot_wider, technically it is not working correctly for each cell (as it's documentation says " Optionally, a function applied to the value in each cell in the output"). NULL is nothing special and length(NULL)=0. I was expecting output as the output of map_dbl as above. The other thing I have noticed problematic, other argument of values_fn (say na.rm of mean) can not be passed to ... (dot dot dot of pivot_wider). Thanks