Aan de slagGa gratis aan de slag

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!

Deze oefening maakt deel uit van de cursus

Introduction to R for Finance

Cursus bekijken

Oefeninstructies

  • 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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

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

# Plot credit_factor_ordered
Code bewerken en uitvoeren