values_fn = length in pivot_wider gives NULL length NA instead of zero

Hi, I think you want values_fill:

dx %>%
  pivot_wider(
    names_from = c(B),
    values_from = c(C),
    names_glue = "{B}_{.value}",
    values_fn = length,
    values_fill = list(C = 0)
  )

out of interest, isn't this just counting, like

dx %>%
  group_by(A, B) %>%
  count() %>%
  pivot_wider(A, names_from = B, values_from = n, values_fill = list(n = 0))

rather than thinking about list columns and length and wide tables?

2 Likes