Create a dfidx object
I've pre-loaded the mlogit package and a data frame called chocolate_df that has the chocolate data in long format. We want to fit a choice model to this data, but first we need to convert it to a dfidx object, the indexed data format that mlogit() requires. This can be tricky, but it is vital to using mlogit() successfully. Before you start writing code, type head(chocolate_df) directly into the console so that you can refer to the column names.
This exercise is part of the course
Choice Modeling for Marketing in R
Exercise instructions
dfidx()needs two index columns: one that identifies the choice question and one that identifies the alternative within that question. I've added achidcolumn tochocolate_dfthat numbers the choice questions. Fill in the two index column names foridx.- Identify the name of the column where the choice is stored and fill it in for
choice. - Use
str()to confirm that you've converted the data to adfidxobject.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# use dfidx() to convert chocolate_df to a dfidx object
chocolate <- dfidx(chocolate_df,
idx = c("____", "____"),
choice = "____")
# use str() to confirm that chocolate is a dfidx object