pivot_wider when there's no value column

You can use the values_fn argument to assign 1 and values_fill to assign 0:

library(tidyr)

pivot_wider(a, names_from = type, values_from = type, values_fn = list(type = ~1), values_fill = list(type = 0))

# A tibble: 3 x 4
  name      a     b     c
  <fct> <dbl> <dbl> <dbl>
1 sam       1     0     0
2 rob       0     1     0
3 tom       0     0     1

We can mutate with a column of 1s and use that in pivot_wider

library(dplyr)
library(tidyr)
a %>%
     mutate(n = 1) %>% 
     pivot_wider(names_from = type, values_from = n, values_fill = list(n = 0))
# A tibble: 3 x 4
#  name      a     b     c
#  <fct> <dbl> <dbl> <dbl>
#1 sam       1     0     0
#2 rob       0     1     0
#3 tom       0     0     1

In base R, it would be easier..

table(a)

Going older school, reshape2::dcast, or the thriving data.table::dcast, let you do this by specifying an aggregate function:

reshape2::dcast(a, name ~ type, fun.aggregate = length)
#   name a b c
# 1  rob 0 1 0
# 2  sam 1 0 0
# 3  tom 0 0 1

data.table::dcast(setDT(a), name ~ type, fun.aggregate = length)
#    name a b c
# 1:  rob 0 1 0
# 2:  sam 1 0 0
# 3:  tom 0 0 1

Tags:

R

Tidyverse