返回模拟定价结果

时间:2021-03-01 10:25:17

标签: r random

我对 R 很陌生,并尝试进行定价模拟。目标是拥有一个长度为 n 的向量,它给出了将收到的优惠券的百分比。当我使用打印时,我得到了我想要的结果。但是,对于我随后的计算,我无法以打印格式处理结果。我尝试用 return 替换它,但这只会给我一个结果。

感谢任何输入。

(用于 rgpd 的包是 POT)

bond_coupon <- function(n, l) {
     events <- rpois(n, l) #simulates the rate of arrival according to a Poisson process
     for (i in 1:length(events)){
         cat <- rgpd(events[i], loc=1000, scale=100, shape=1) #simulates the severance of each event
         if(events[i]>1){
             coupon <- prod(1-((cat-1000)/cat))
         } else if(events[i]==1){
             coupon<- 1-((cat-1000)/cat)
         } else{
             coupon<- 1.00
         }
         print(coupon)
     }
 }

1 个答案:

答案 0 :(得分:0)

您的 coupon 在每次循环迭代时都会被覆盖,因此 return 只返回最后一个。

您可以创建一个向量 coupon 并在每次迭代时填充它:

bond_coupon <- function(n, l) {
  events <- rpois(n, l) #simulates the rate of arrival according to a Poisson process
  coupon = numeric(length(events))
  for (i in 1:length(events)){
    cat <- rgpd(events[i], loc=1000, scale=100, shape=1) #simulates the severance of each event
    if(events[i]>1){
      coupon[i] <- prod(1-((cat-1000)/cat))
    } else if(events[i]==1){
      coupon[i]<- 1-((cat-1000)/cat)
    } else{
      coupon[i]<- 1.00
    }
  }
  return(coupon)
}

或者,您可以将创建和循环委托给 apply 系列函数:

bond_coupon <- function(n, l) {
  #simulates the rate of arrival according to a Poisson process
  events <- rpois(n, l)
  
  coupon <- sapply(X = seq_along(events), FUN = function(i) {
      #simulates the severance of each event
      cat <- rgpd(events[i], loc = 1000, scale = 100, shape = 1)
      
      if (events[i] > 1) {
        prod(1 - ((cat - 1000) / cat))
      } else if (events[i] == 1) {
        1 - ((cat - 1000) / cat)
      } else {
        1.00
      }
    }
  )
  return(coupon)
}
相关问题