实际上,我想为每个credit_category分配特定的风险权重。
我一直在使用嵌套的ifelse,如下所示,但是我试图找到其他东西以避免嵌套,而不使用“ dplyr”库。 有什么想法吗?
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
)))))))))
答案 0 :(得分:0)
您可以使用命名向量来创建查找表:
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)
答案 1 :(得分:0)
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')
recode
函数非常易于使用。