Model.matrix doesn't give me the right output

Hi,

I am new with Rstudio so maybe this is a stupid question.

I have to conduct a one-way ANOVA (with appropriate constrain) on the chick weight with respect to the six feed supplements, without using the aov or lm functions.

First of all I am trying to create a incindence matrix with ones and zeros. I used the function model.matrix but now I have one column to less. I used the code: model.matrix(~feed) and I obtained the next image.

30

In this image you see the first 10 rows of the matrix. But I am missing the casein column and also the order is changed.

Could please some help me out

Thanks in advance

This is intended. If "casein" also had a dummy column, it would be a linear combination of the other columns (if it's not NA or one of the other levels, it has to be "casein"). This is often the most useful form, so it's what the function returns. If you need to add the column, it shouldn't be hard.

mm <- model.matrix(~ feed, data = chickwts)
mm <- cbind(mm, feedcasein = rowSums(mm[, -1]) == 0)
head(mm)
#   (Intercept) feedhorsebean feedlinseed feedmeatmeal feedsoybean feedsunflower feedcasein
# 1           1             1           0            0           0             0          0
# 2           1             1           0            0           0             0          0
# 3           1             1           0            0           0             0          0
# 4           1             1           0            0           0             0          0
# 5           1             1           0            0           0             0          0
# 6           1             1           0            0           0             0          0

It looks like the correct order to me.

> levels(chickwts[["feed"]])
# [1] "casein"    "horsebean" "linseed"   "meatmeal"  "soybean"   "sunflower"
1 Like

Thanks for your help!

If you use cbind, the column will be added at the end of the matrix, so the "casein" is now the last column and thats why I am talking about changing the order. Because afterwards I have to multiply matrices and I do get other results right?