Original data frame:
v1 = sample(letters[1:3], 10, replace=TRUE)
v2 = sample(letters[1:3], 10, replace=TRUE)
df = data.frame(v1,v2)
df
There is a function in caret's package that does what you require, dummyVars. Here is the example of it's usage taken from the authors documentation: http://topepo.github.io/caret/preprocess.html
library(earth)
data(etitanic)
dummies <- caret::dummyVars(survived ~ ., data = etitanic)
head(predict(dummies, newdata = etitanic))
pclass.1st pclass.2nd pclass.3rd sex.female sex.male age sibsp parch
1 1 0 0 1 0 29.0000 0 0
2 1 0 0 0 1 0.9167 1 2
3 1 0 0 1 0 2.0000 1 2
4 1 0 0 0 1 30.0000 1 2
5 1 0 0 1 0 25.0000 1 2
6 1 0 0 0 1 48.0000 0 0
The model.matrix options could be useful in case you had sparse data and wanted to use Matrix::sparse.model.matrix