0

Actually, I want to assign to each credit_category a specific Risk-weight.

I've been using nested ifelse as shown below, but I am trying to find something else in order to avoid the nesting, without using "dplyr" library. Any ideas ?

tab_nonsec$RW = ifelse(tab_nonsec$credit_category=="AAA", 0.005,
                       ifelse(tab_nonsec$credit_category=="AA", 0.02,
                       ifelse(tab_nonsec$credit_category=="A", 0.03,
                       ifelse(tab_nonsec$credit_category=="BBB", 0.06,
                       ifelse(tab_nonsec$credit_category=="BB", 0.15,
                       ifelse(tab_nonsec$credit_category=="B", 0.3,
                       ifelse(tab_nonsec$credit_category=="CCC", 0.5,
                       ifelse(tab_nonsec$credit_category=="Unrated", 0.75,
                       ifelse(tab_nonsec$credit_category=="Defaulted",1,0
                       )))))))))
momo96
  • 53
  • 4

2 Answers2

1
car::recode(test, '"AAA"=0.005;
                  "AA"=0.02;
                  "A"=0.03;
                  "BBB"=0.06;
                  "BB"=0.15;
                  "B"=0.3;
                  "CCC"=0.5;
                  "Unrated"=0.75;
                  "Defaulted"=1')

The recode function is pretty easy to use.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
DSGym
  • 2,807
  • 1
  • 6
  • 18
  • If I had many categories to recode I would probably try to get the cateogories in a csv and use the vectorized `mutate` function to recode my data :-) – DSGym Jun 07 '19 at 09:27
0

You can used a named vector to make a lookup table:

lut <- c(
  "AAA" = 0.005, "AA" = 0.02, "A" = 0.03, 
  "BBB" = 0.06, "BB" = 0.15, "B" = 0.3, 
  "CCC" = 0.5, 
  "Unrated" = 0.75, 
  "Defaulted" = 1
)

tab_nonsec$RW <- lut[tab_nonsec$credit_category]
tab_nonsec$RW[is.na(tab_nonsec$RW)] <-0

#   credit_category    RW
# 1              AA 0.020
# 2             CCC 0.500
# 3             AAA 0.005
# 4               B 0.300
# 5             AAA 0.005
# 6       Defaulted 1.000
# 7             BBB 0.060
# 8             BBB 0.060
# 9          errror 0.000

# Example data:

tab_nonsec <- data.frame(credit_category = c("AA", "CCC", "AAA", "B", "AAA", "Defaulted", "BBB", "BBB", "errror"), stringsAsFactors = FALSE)
s_baldur
  • 29,441
  • 4
  • 36
  • 69