Transform a data frame into a matrix using one hot encoding.
as_model_matrix(df, intercept = FALSE)
A data frame.
Whether to have a column with all 1
s. Default is FALSE
.
A matrix.
mat <- as_model_matrix(iris)
str(mat)
#> num [1:150, 1:7] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#> - attr(*, "dimnames")=List of 2
#> ..$ : chr [1:150] "1" "2" "3" "4" ...
#> ..$ : chr [1:7] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
#> - attr(*, "assign")= int [1:7] 1 2 3 4 5 5 5
#> - attr(*, "contrasts")=List of 1
#> ..$ Species: chr "contr.treatment"