simul()无法在表达式中找到变量

时间:2017-02-22 17:21:38

标签: r object

执行以下代码时出现以下错误。它似乎是由于没有分配全局参数,但是,当ncfn和ncfp被指定为全局时,这似乎会产生问题。请你帮忙

#Install libraries
library(MASS)
library(actuar)

#Set globals
set.seed(1)
sims<-10

#Set claim frequency
claim_freq_n<-5
claim_freq_p<-0.5

#Create function to simulate claim severity, set n globally as number of claims to generate, set m globally as parameters of severity distribution
claimsev<-function(n,m) { 
  rep(100,n) #use for testing
}

#Create function to generate two tables, first table has all projected losses, second table has number of losses by simulation.
SimX<-function(ncfn,ncfp,nyr)    { 
  #sims  = number of simulations

  #The expressions for ms and mf are dependent on the parameters being set at global level, so need << assignment and removal at end of these global values

  nodes <- list(year = nyr)
  mf <- expression(year=rnbinom(ncfn,ncfp))
  ms <- expression(year=claimsev(global_m))
  pf <- simul(nodes, mf, ms)

  #now clean up
  rm(list=grep("glob", ls(1), value=T), envir=globalenv())

  #check
  global_test<<-frequency(pf,classification=FALSE)
  print(fm<-mean(frequency(pf,classification=FALSE)))
  sf<-severity(pf, by = "year")   #see severity claims by year
  sn<-as.numeric(frequency(pf,classification=FALSE)) 

  return(list(sf$main,sn))
}

#Apply per claim and policy deductibles and limits
z<-SimX(claim_freq_n,claim_freq_p,sims) 

rnbinom中的错误(ncfn,ncfp,n = 10):object&#39; ncfn&#39;找不到

1 个答案:

答案 0 :(得分:1)

simul函数中,他们会评估您传入的表达式

eval(Call)

因为它们没有明确指定评估该表达式的环境,所以它在simul函数的环境中进行评估,该函数不包含变量ncfn。该变量是在SimX函数的环境中定义的。请注意,在调用函数的环境中不搜索变量,而是R在词法范围内,因此在定义函数的环境中查找变量。因此,simul无法找到ncfn的值。

解决方案是在调用simul之前评估这些参数。这是一种方式

mf <- as.expression(c(year=bquote(rbindom(.(ncfn), .(ncfp)))))
# or
mf <- as.expression(c(year=substitute(rbindom(n, p), list(n=ncfn, p=ncfp))))

这将改为

mf
# expression(year = rbindom(5, 0.5))

然后可以安全地传递到simul(),因此没有需要查找的变量。

您也会对ms执行相同的操作。无法对其进行测试,因为您的示例中未定义global_m