MATLAB Examples

Reorder Category Levels in Nominal Arrays

This example shows how to reorder the category levels in nominal arrays using reorderlevels. By definition, nominal array categories have no natural ordering. However, you might want to change the order of levels for display or analysis purposes. For example, when fitting a regression model with categorical covariates, fitlm uses the first level of a nominal independent variable as the reference category.

Contents

Load sample data.

The dataset array, hospital, contains variables measured on 100 sample patients. The variable Weight contains the weight of each patient. The variable Sex is a nominal variable containing the gender, Male or Female, for each patient.

load hospital
getlevels(hospital.Sex)
ans = 

  1x2 nominal array

     Female      Male 

By default, the order of the nominal categories is in ascending alphabetical order of the labels.

Plot data grouped by category level.

Draw box plots of weight, grouped by gender.

figure
boxplot(hospital.Weight,hospital.Sex)
title('Weight by Gender')

The box plots appear in the same alphabetical order returned by getlevels.

Change the category order.

Change the order of the category levels.

hospital.Sex = reorderlevels(hospital.Sex,{'Male','Female'});
getlevels(hospital.Sex)
ans = 

  1x2 nominal array

     Male      Female 

The levels are in the newly specified order.

Plot data in new order.

Draw box plots of weight by gender.

figure
boxplot(hospital.Weight,hospital.Sex)
title('Weight by Gender')

The order of the box plots corresponds to the new level order.