![]() The code below is an example of how you can include the baseline level for all factor variables in the data frame. It’s easy to modify the code above to include the baseline level for a different factor variable in another data frame. If we didn’t pass this special value in, the default would have had just 2 columns, one for each of the levels we see in the output: contrasts(iris$Species, contrasts = TRUE) Notice that there are 3 columns, one for each level. Let’s have a closer look at what we passed as the value of Species in the list: contrasts(iris$Species, contrasts = FALSE) # (Intercept) Speciessetosa Speciesversicolor Speciesvirginica (For example, when we do regularized regression, since multi-collinearity is no longer implies unidentifiability of the model.) We can induce this behavior by passing a specific value to the contrasts.arg argument: x <- model.matrix(Ĭontrasts.arg = list(Species = contrasts(iris$Species, contrasts = FALSE))) However, there are situations where we might want dummy variables to be produced for all levels including the baseline level. This is to avoid the problem of multi-collinearity. For a factor variable, model.matrix treats the first level it encounters as the “baseline” level and will not produce a dummy variable for it. Also note that while the Species factor has 3 levels (“setosa”, “versicolor” and “virginica”), the return value of model.matrix only has dummy variables for the latter two levels. Model.matrix returns a column of ones labeled (Intercept) by default. # (Intercept) Speciesversicolor Speciesvirginica X <- model.matrix(Sepal.Length ~ Species, iris) # $ Species : Factor w/ 3 levels "setosa","versicolor".: 1 1 1 1 1 1 1 1 1 1. Let’s see this in action on the iris dataset: data(iris) ![]() In particular, it is used to expand factor variables into dummy variables (also known as “ one-hot encoding“). In R, the model.matrix function is used to create the design matrix for regression. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |