1. Learn
  2. /
  3. Courses
  4. /
  5. Introduction to R for Finance

Exercise

stringsAsFactors

Do you remember back in the data frame chapter when you used str() on your cash data frame? This was the output:

str(cash)

'data.frame':    3 obs. of  3 variables:
 $ company  : Factor w/ 2 levels "A","B": 1 1 2
 $ cash_flow: num  100 200 300
 $ year     : num  1 3 2

See how the company column has been converted to a factor? R's default behavior when creating data frames is to convert all characters into factors. This has caused countless novice R users a headache trying to figure out why their character columns are not working properly, but not you! You will be prepared!

To turn off this behavior:

cash <- data.frame(company, cash_flow, year, stringsAsFactors = FALSE)

str(cash)

'data.frame':    3 obs. of  3 variables:
 $ company  : chr  "A" "A" "B"
 $ cash_flow: num  100 200 300
 $ year     : num  1 3 2

Instructions

100 XP
  • Two variables, credit_rating and bond_owners have been defined for you. bond_owners is a character vector of the names of some of your friends.
  • Create a data frame named bonds from credit_rating and bond_owners, in that order, and use stringsAsFactors = FALSE.
  • Use str() to confirm that both columns are characters.
  • bond_owners would not be a useful factor, but credit_rating could be! Create a new column in bonds called credit_factor using $ which is created from credit_rating as a correctly ordered factor.
  • Use str() again to confirm that credit_factor is an ordered factor.