Get startedGet started for free

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

View Course

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 a chid column to chocolate_df that numbers the choice questions. Fill in the two index column names for idx.
  • 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 a dfidx object.

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
Edit and Run Code