# R gives me the error “contrasts can be applied only to factors with 2 or more levels” running an mlogit model, but all my factors have 2 levels [closed]

I have a set of results from a choice experiment that I am trying to analyse using the mlogit function in R. My data set is shown below, where each STR value represents the three choices in a single choice experiment, 'CHOICE' is a binary variable indicating which the participant selected, and columns C-G detail the attributes of each choice (D-G being binary variables - 1=yes, 0=no).

I am trying to run the model as:

m <- mlogit(CHOICE ~ PRICE + GreenStatement + Certification +
MediumBrand + HighBrand,
SP1, choice = "CHOICE", shape = "long", alt.levels = "STR")


but get the error "contrasts can be applied only to factors with 2 or more levels". I have tried running 'as.factor' on all the variables, so they are different factors, and asking R to display a data summary tells me that they all have 2 or more levels. But I still get this error. Would anyone please be able to help me identify (and fix!) the source of this error?

Thanks.

## closed as off-topic by Sven Hohenstein, Nick Cox, Peter Flom♦Apr 8 '16 at 11:30

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "This question appears to be off-topic because EITHER it is not about statistics, machine learning, data analysis, data mining, or data visualization, OR it focuses on programming, debugging, or performing routine operations within a statistical computing platform. If the latter, you could try the support links we maintain." – Sven Hohenstein, Nick Cox, Peter Flom
If this question can be reworded to fit the rules in the help center, please edit the question.

• Are you sure that everything you think is a factor is? try putting as.factor into the mlogit function, as in mlogit(CHOICE ~ PRICE + as.factor(GreenStatement) ... – Jeremy Miles Mar 13 '15 at 23:06
• What do is.factor(SP1$CHOICE) and unique(SP1$CHOICE) and levels(SP1\$CHOICE) return? – shadowtalker Mar 14 '15 at 10:59
• Do that for all of them. Especially MediumBrand since from the screen cap it looks like a column of zeroes – shadowtalker Mar 14 '15 at 11:01
• They all give me the same output: is.factor(VARIABLE) [1] TRUE ; unique(VARIABLE) [1] 0 1 Levels: 0 1 ; levels(VARIABLE) [1] "0" "1" – elephants_neve_forget Mar 15 '15 at 10:11
• The help on mlogit doesn't list an alt.levels argument -- what does it do? – Glen_b Nov 17 '15 at 6:14

• Here's a way to check this if dt is a data.table: char.factor.cols <- names(which(sapply(dt, function(x) is.character(x) | is.factor(x)))); for(i in char.factor.cols) cat(i, dt[, .N, i][, .N], "\n") – Max Ghenis Mar 24 '17 at 22:01
• for a plain data frame, df, you can use: which(sapply(df, function(x) (is.character(x) | is.factor(x)) & length(unique(x))<2)) – Roobie Nuby May 14 '17 at 23:12