Get a prediction from the new data inputted against the model, but an error is produced, how to adapt the R code for it to work?
This is a quite common mistake, you transformed the test and training data separately which messes with factor levels.

There are multiple solutions to this:

1) Create a common transformer

If you there is no "new" data but simply a test set (e.g. like in kaggle competitions or similar problems) you should create a function that transforms / tidies ALL data at once and only split the data after it already has the proper form for the modelling (including OHE, etc.).

2) Save your factor levels!

For all other case you should save your factor levels and create a transformer accordingly. Here is a code example:

text_levels &lt;- levels(train$text)

levels(test$text) &lt;- text_levels


Realize also, that any word or factor level not present in the data you train your model on cannot be considered in the model and therefore is useless! All above solutions simply add the appropriate factor levels from the training model if they are missing in the test data.

If you have new words in the test data you will simply need to drop them before transforming the data as they are not used in the prediction model.