I'm messing around with R and came across some code using the tilde operator and Model.Matrix in a way I can't really quite figure out. I produced a very simple example below.
data("iris")
x = model.matrix(~Species +0, iris)
x
Here's a quick snapshot of the data selecting 3 random rows with different species:
>iris[c(1,78, 143),]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
78 6.7 3.0 5.0 1.7 versicolor
143 5.8 2.7 5.1 1.9 virginica
and of the same row but after it's been put through model.matrix:
> x[c(1,78,143),]
Speciessetosa Speciesversicolor Speciesvirginica
1 1 0 0
78 0 1 0
143 0 0 1
As you can see this output output creates a matrix of 3 columns, and 150 rows (the same number of observations). In each row the corresponding species of flower is labeled 1. This is really neat but I can't really understand how or why this is working exactly.
I'm confused on two elements.
- what exactly is model.matrix doing here. When I bring up the help menu in RStudio it simply
model.matrix creates a design (or model) matrix, e.g., by expanding factors to a set of dummy variables (depending on the contrasts) and expanding interactions similarly.
I don't really quite follow what this means. What does it mean when it says "expanding factors" to a set of dummy variables?
- Also, how is the tilde operator being used here? Usually when I have seen the tilde operator, it separates the Y and the Xs as in
lm(Y ~ X1+X2-X3)or the like. I've never seen it used nakedly here.
if I just run something similar in the console without the wrapping of model.matrix like so:
> ~iris$Species
I only get this as the output:
~iris$Species
Which honestly seems like an error, but I assume since R doesn't tell me it is an error that it's not actually.