Get Started

Create an ordered factor

Look at the plot created over on the right. It looks great, but look at the order of the bars! No order was specified when you created the factor, so, when R tried to plot it, it just placed the levels in alphabetical order. By now, you know that there is an order to credit ratings, and your plots should reflect that!

As a reminder, the order of credit ratings from least risky to most risky is:

AAA, AA, A, BBB, BB, B, CCC, CC, C, D

To order your factor, there are two options.

When creating a factor, specify ordered = TRUE and add unique levels in order from least to greatest:

credit_rating <- c("AAA", "AA", "A", "BBB", "AA", "BBB", "A")

credit_factor_ordered <- factor(credit_rating, ordered = TRUE, 
                                levels = c("AAA", "AA", "A", "BBB"))

For an existing unordered factor like credit_factor, use the ordered() function:

ordered(credit_factor, levels = c("AAA", "AA", "A", "BBB"))

Both ways result in:

credit_factor_ordered

[1] AAA AA  A   BBB AA  BBB A  
Levels: AAA < AA < A < BBB

Notice the < specifying the order of the levels that was not there before!

This is a part of the course

“Introduction to R for Finance”

View Course

Exercise instructions

  • The character vector credit_rating is in your workspace.
  • Use the unique() function with credit_rating to print only the unique words in the character vector. These will be your levels.
  • Use factor() to create an ordered factor for credit_rating and store it as credit_factor_ordered. Make sure to list the levels from least to greatest in terms of risk!
  • Plot credit_factor_ordered and note the new order of the bars.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Use unique() to find unique words
unique(___)

# Create an ordered factor
credit_factor_ordered <- factor(___, ordered = ___, levels = c(___))

# Plot credit_factor_ordered
Edit and Run Code

This exercise is part of the course

Introduction to R for Finance

BeginnerSkill Level
4.8+
12 reviews

Learn essential data structures such as lists and data frames and apply that knowledge directly to financial examples.

Questions with answers that fall into a limited number of categories can be classified as factors. In this chapter, you will use bond credit ratings to learn all about creating, ordering, and subsetting factors.

Exercise 1: What is a factor?Exercise 2: Create a factorExercise 3: Factor levelsExercise 4: Factor summaryExercise 5: Visualize your factorExercise 6: Bucketing a numeric variable into a factorExercise 7: Ordering and subsetting factorsExercise 8: Create an ordered factor
Exercise 9: Subsetting a factor

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free