Manually Changing The Pivot Table Column Order The Way You Want

Here’s a Pivot table showing % of Total of each state for each airline carrier.

The columns, the airline carries, are now ordered alphabetically. But let’s say you want to show DL (Delta Airline) and UA (United Airline) first then show the rest.

You can do some data wrangling to set the order for the carrier column (CARRIER) with fct_relevel function.

Select ‘Work with Factor (Category)’ -> ‘Set Order Manually’.

In the Mutate dialog, you will see fct_relevel function is automatically pre-populated. Inside the function, you can start adding the values in the order you want.

I’m selecting just “UA” and “DL”, so that the carriers will be ordered as “UA”, “DL”, and the rest (“AA”, “AS”, and so on).

Once that’s done, then re-open the Pivot Table.

And here it is.

By the way, fct_relevel function convert the original column data type to Factor, which can hold the order information along with the values themselves. It is one of the amazing things that R supports from the beginning. If you want to know more about Factor, take a look at this blog post!