Get startedGet started for free

Create a factor

Bond credit ratings are common in the fixed income side of the finance world as a simple measure of how "risky" a certain bond might be. Here, riskiness can be defined as the probability of default, which means an inability to pay back your debts. The Standard and Poor's and Fitch credit rating agency has defined the following ratings, from least likely to default to most likely:

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

This is a perfect example of a factor! It is a categorical variable that takes on a limited number of levels.

To create a factor in R, use the factor() function, and pass in a vector that you want to be converted into a factor.

Suppose you have a portfolio of 7 bonds with these credit ratings:

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

To create a factor from this:

factor(credit_rating)

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

A new character vector, credit_rating has been created for you in the code for this exercise.

This exercise is part of the course

Introduction to R for Finance

View Course

Exercise instructions

  • Turn credit_rating into a factor using factor(). Assign it to credit_factor.
  • Print out credit_factor.
  • Call str() on credit_rating to note the structure.
  • Call str() on credit_factor and compare the structure to credit_rating.

Hands-on interactive exercise

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

# credit_rating character vector
credit_rating <- c("BB", "AAA", "AA", "CCC", "AA", "AAA", "B", "BB")

# Create a factor from credit_rating
credit_factor <- 

# Print out your new factor


# Call str() on credit_rating


# Call str() on credit_factor
Edit and Run Code