How can I tell R to use a certain level as reference if I use binary explanatory variables in a regression?
It's just using some level by default.
lm(x ~ y + as.factor(b))
with b {0, 1, 2, 3, 4}
. Let's say I want to use 3 instead of the zero that is used by R.
Others have mentioned the relevel command which is the best solution if you want to change the base level for all analyses on your data (or are willing to live with changing the data).
If you don't want to change the data (this is a one time change, but in the future you want the default behavior again), then you can use a combination of the C (note uppercase) function to set contrasts and the contr.treatments function with the base argument for choosing which level you want to be the baseline. For example:
See the
relevel()
function. Here is an example:Now alter the factor
b
inDF
by use of therelevel()
function:The models have estimated different reference levels.
I know this is an old question, but I had a similar issue and found that:
does exactly what you asked.
You can also manually tag the column with a
contrasts
attribute, which seems to be respected by the regression functions:The
relevel()
command is a shorthand method to your question. What it does is reorder the factor so that whatever is the ref level is first. Therefore, reordering your factor levels will also have the same effect but gives you more control. Perhaps you wanted to have levels 3,4,0,1,2. In that case...I prefer this method because it's easier for me to see in my code not only what the reference was but the position of the other values as well (rather than having to look at the results for that).
NOTE: DO NOT make it an ordered factor. A factor with a specified order and an ordered factor are not the same thing.
lm()
may start to think you want polynomial contrasts if you do that.