【发布时间】:2020-09-28 08:07:18
【问题描述】:
我正在尝试使用 for 循环模拟 1,000 个投资组合,每个投资组合中有 3 只债券,并找出三分之二的债券违约的概率。 这是我的代码(使用 cmets):
#Reproducibility
set.seed(33)
#Number of trials
n<-1000
#Initialize variables
numberofdefaults<-0
counter<-0
portfolio <- 0
for (i in 1:n){
portfolio[i] <- rbinom(3, 1, prob = 0.127) # generate three random binomial deviates with probabiltiy of sucess("default" in my case)0.127 and store them in a vector
numberofdefaults[i] <- sum(portfolio[i] == 1) # find the number of defaults in the vector (1 for default) and add them up
if (numberofdefaults[i] == 2) { # if number of defaults is 2, then add 1 to the counter
counter<-counter+1
}
}
当我执行代码时,我不断收到一条错误消息:要替换的项目数不是替换长度的倍数
非常感谢您抽出宝贵的时间。任何建议将不胜感激。
【问题讨论】: