The workaround I found is to first convert the factor variables in your train and test suite to characters
test$factor <- as.character(test$factor)
Then add a column for each with a flag for test / train, i.e.
test$isTest <- rep(1,nrow(test)) train$isTest <- rep(0,nrow(train))
Then return them
fullSet <- rbind(test,train)
Then convert back to coefficient
fullSet$factor <- as.factor(fullSet$factor)
This ensures that both sets of tests and trains have the same levels. Then you can deselect:
test.new <- fullSet[fullSet$isTest==1,] train.new <- fullSet[fullSet$isTest==0,]
and you can drop / NULL from the isTest column from each. Then you will have sets with the same levels that you can train and test. It might have been a more elegant solution, but it worked for me in the past, and you can write it into a small function if you need to repeat it often.
source share