0

I'm a beginner to R and ran into an error while trying to use the optim function.

I have a likelihood equation that I'd like to maximize, so I've implemented the following code:

>datafile=read.delim("clipboard")

> log.lik=function(theta, x, mu){
+ b=theta[1]
+ beta=theta[2]
+ tau=theta[3]
+ result=function(b,beta, tau){(-sum(x)/b)-sum(log(-beta*(x-tau)))-sum(log(integrate(exp(-x/b)/(1+exp(-beta(x-tau)))), lower=1500, upper=Inf))}
+ return(result)
+ }
> estimate=c(1,1,1)
> model=optim(par=estimate, fn=log.lik, control=list(fnscale=-1), x=datafile, mu=1500)

Everything works until the optim function at which I get the following error message: Error in optim(par = estimate, fn = log.lik, control = list(fnscale = -1), : cannot coerce type 'closure' to vector of type 'double'

Would anyone have an idea of what might be the issue here? Any help would be appreciated!

The data file is just one column of simulated financial losses in a csv format. When I output the datafile variable here's a sample of what I get:

       X1946774
1      34949037
2     734018898
3     393502463
4     388573133
5      93213300
6      74982868
7      55322550
8      10828207
9       4530577
10      3786748
11      2041762
12    342745985
13    292313639
14    259569928
15    143871771
16     53691635
17     24489644
18     20506718
19     14281945

Edited code incorporating changes from comments:

 > log.lik=function(theta,x,mu){
    + b=theta[1]
    + beta=theta[2]
    + tau=theta[3]
    + integrand<-function(x,b,beta,tau){exp(-x/b)/(1+exp(-beta*(x-tau)))}
    + result<-(-sum(x)/b)-sum(log(-beta*(x-tau)))-sum(log(integrate(integrand, lower=mu, upper=Inf)))
    + return(result)
    + }
    > model=optim(par=estimate, fn=log.lik, control=list(fnscale=-1), x=datafile, mu=1500)
4

1 回答 1

1

评论太长了。

首先,您仍然使用integrate(...)不正确。这个函数返回一个列表(阅读文档!!)。此列表的$value元素是积分。因此,要找到ffroma到的积分b,请使用:

integrate(f,a,b,...)$value

可悲的是,这是您遇到的最少的问题。从根本上说,你走的捷径太多了。你不能只是把一些代码放在一起——你需要注意数学

例如,您是否integrand(...)为 的初始值绘制了函数的值theta,范围为(mu,Inf)?? 如果你有,你会看到被积函数在这个范围内是 0,因为mu=1500and b=1, andexp(-1500/1)在数值上是 0;因此积分为 0,积分的对数未定义。此外,您的目标函数包括术语log(-beta*(x-tau)), 但对于beta=tau=1,-beta*(x-tau) < 0用于x数据集中的所有 , 并且再次未定义日志。

为了记录,我没有否决你的问题(因为我觉得这种做法令人反感......),但你确实需要努力了解你的对数似然函数是否正确,当你这样做时,采取仔细看看你的初步估计。

于 2014-08-04T22:22:08.563 回答