Q:

In R, how can I add mulitple columns with 0/1 count based on another column?

Using the mtcars dataset in R as an example I want to add extra columns to the mtcars dataframe for each type of car.
With this line I can get the car models:
unique(sapply((strsplit(row.names(mtcars), " ")), "[[", 1))

Which would be 22 extra columns I want to add. A new column for each car model:
length(unique(sapply((strsplit(row.names(mtcars), " ")), "[[", 1)))

What I have come up with is this code:
mtcars01 <- mtcars
car.nms <- sapply((strsplit(row.names(mtcars), " ")), "[[", 1)
mtcars01$Mazda <- (car.nms=="Mazda")*1
mtcars01$Datsun <- (car.nms=="Datsun")*1
mtcars01$Hornet <- (car.nms=="Hornet")*1

And so on, and so on... Going through all the car models, until I have a new column added for each car model, with zeroes and ones. This is what I am after. I could then loop over all the unique car models, but I would prefer not to add a loop. If possible.
My own input data frame looks similar to the mtcars dataset, but I have a different number of car models, and would like to reuse this code for data frames where the number of car models vary. My own data frame might only have 3 car models, I would then need to have 3 extra columns appended to my data frame with zeroes and ones for these car models. I have marked this question with 'aggregate' and 'dplyr' as they appear promising. But I might be wrong on this part. Thanks for any help. Sorry if I overlooked an answer.

A:

One option would be  to loop through the unique elements of 'car.nms', compare (==) with the values of 'car.nms' and coerce the logical matrix to binary (+)
mtcars01[unique(car.nms)] <- +(sapply(unique(car.nms), `==`,  car.nms))

Or using tidyverse, get the first word of the row names with word (from stringr), pull the rowname column, use mtabulate (from qdapTools) and bind the columns with the original data
library(tidyverse)
library(qdapTools)
rownames_to_column(mtcars) %>%
     mutate(rowname = word(rowname)) %>% 
     pull(rowname) %>% 
     mtabulate %>% 
     bind_cols(mtcars, .)

