Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set specific contrasts in multinom() in nnet package?

I have a 3-class problem that needs classification. I want to use the multinomial logistic regression in nnet package. The Class outcome has 3 factors, P, Q, R. I want to treat Q as the base factor.

So I tried to write it the contrasts like this:

P <- c(1,0,0)
R <- c(0,0,1)
contrasts(trainingLR$Class) <- cbind(P,R)

checked it:

> contrasts(trainingLR$Class)
  P R
P 1 0
Q 0 0
R 0 1 

Now multinom():

library(nnet)
multinom(Class ~., data=trainingLR)

Output:

> multinom(Class ~., data=trainingLR)
# weights:  39 (24 variable)
initial  value 180.172415 
iter  10 value 34.990665
iter  20 value 11.765136
iter  30 value 0.162491
iter  40 value 0.000192
iter  40 value 0.000096
iter  40 value 0.000096
final  value 0.000096 
converged
Call:
multinom(formula = Class ~ ., data = trainingLR)

Coefficients:
  (Intercept)        IL8     IL17A      IL23A     IL23R
Q   -116.2881 -16.562423 -34.80174   3.370051  6.422109
R    203.2414   6.918666 -34.40271 -10.233787 31.446915
       EBI3     IL6ST     IL12A   IL12RB2     IL12B
Q -8.316808  12.75168 -7.880954  5.686425 -9.665776
R  5.135609 -20.48971 -2.093231 37.423452 14.669226
    IL12RB1    IL27RA
Q -6.921755 -1.307048
R 15.552842 -7.063026

Residual Deviance: 0.0001922658 
AIC: 48.00019 

Question:
So as you see, since P class didn't appear in the output, it means that it was treated as base being the first one in alphabetical order as expected when dealing with factor variables in R, and Q class was not treated as base level in this case, how to make it base to the other two levels?

like image 251
doctorate Avatar asked Feb 05 '14 09:02

doctorate


1 Answers

I tried to avoid using contrasts and I discovered the relevel function for choosing a desired level as baseline. The following code

trainingLR$Class <- relevel(trainingLR$Class, ref = "P")

should set "P" level as your baseline. Therefore, try the same thing with "Q" or "R" levels.

The R Documentation (?relevel) mentions "This is useful for contr.treatment contrasts which take the first level as the reference."

Though might be too late to answer now, but since others might be interested, I thought is worthwhile sharing the above option.

like image 82
Valentin Avatar answered Nov 01 '22 15:11

Valentin