how to force model.matrix to use all levels of 2 categorical variables?

DescriptionI have 2 categorical variables and I want to turn them into columns - for each category exactly one column

ProgressSimple code to achive this:

d.data <- data.frame(a=as.factor(c("some1","some2","some3")), b = as.factor(c("other1","other3","other2")))
d.data.new <- data.frame(model.matrix(~a -1 + b -1, data=d.data))
names(d.data.new)

[1] "asome1" "asome2" "asome3" "bother2" "bother3"

"-1" works only for "a" variable which is represented by whole 3 levels, but "b" have only two - and I need whole 3. Not really undarstand how "-1" works in this case for {formula} inside model.matrix

Not a model.matrix solution, but you can get the binary output usingmtabulate

library(qdapTools)
mtabulate(as.data.frame(t(d.data)))

Or another option would be to loop through the column names of 'd.data' and do themodel.matrixseparately on each column,cbindand change the column names (if required).

d1 <- do.call(cbind,lapply(names(d.data), function(i) 
                      model.matrix(~get(i)-1, d.data)))
colnames(d1) <- sub('.*\\)', '', colnames(d1))