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: <- data.frame(a=as.factor(c("some1","some2","some3")), b = as.factor(c("other1","other3","other2"))) <- data.frame(model.matrix(~a -1 + b -1,

[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


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

d1 <-,lapply(names(, function(i) 
colnames(d1) <- sub('.*\\)', '', colnames(d1))