Spread columns by count in R dplyr

Update for tidyr::pivot_wider:

library(tidyverse)

car_type %>% 
  count(car, type) %>% 
  pivot_wider(names_from=type, values_from=n, values_fill=0)

Original Answer

With reshape2:

library(reshape2)

dcast(car_type, car ~ type)

If you were going to use dplyr, the code would be:

dplyr and reshape2

car_type %>% count(car, type) %>%
  dcast(car ~ type, fill=0)

dplyr and tidyr

car_type %>% count(car, type) %>%
  spread(type, n, fill=0)

In each case, count(car, type) is equivalent to

group_by(car, type) %>% tally

or

group_by(car, type) %>% summarise(n=n())

With data.table

library(data.table)

dcast(setDT(car_type), car ~ type, fill=0)

Try this in base R:

xtabs(~car+type, car_type)

#   type
#car bad good regular
#  a   0    2       0
#  b   2    2       2
#  c   2    0       2

OR

table(car_type)