为什么我要估算的参数“未找到"? [英] Why the parameter I am trying to estimate is "not found"?
问题描述
我正在尝试使用优化估计al_j
,au_j
,b_j
和sigma_j
来优化R_j
和R_m
的似然函数.这就是我所做的.
I am trying to optimise my likelihood function of R_j
and R_m
using optim to estimate al_j
, au_j
, b_j
and sigma_j
. This is what I did.
a = read.table("D:/ff.txt",header=T)
attach(a)
a
R_j R_m
1 2e-03 0.026567295
2 3e-03 0.009798475
3 5e-02 0.008497274
4 -1e-02 0.012464578
5 -9e-04 0.002896023
6 9e-02 0.000879473
7 1e-02 0.003194435
8 6e-04 0.010281122
需要估计参数al_j,au_j,b_j和sigma_j.
llik=function(R_j,R_m)
if(R_j< 0)
{
sum[log(1/(2*pi*(sigma_j^2)))-(1/(2*(sigma_j^2))*(R_j+al_j-b_j*R_m))^2]
}else if(R_j>0)
{
sum[log(1/(2*pi*(sigma_j^2)))-(1/(2*(sigma_j^2))*(R_j+au_j-b_j*R_m))^2]
}else if(R_j==0)
{
sum(log(pnorm(au_j,mean=b_j*R_m,sd=sigma_j)-pnorm(al_j,mean=b_j*R_m,sd=sigma_j)))
}
start.par=c(al_j=0,au_j=0,sigma_j=0.01,b_j=1)
out1=optim(llik,par=start.par,method="Nelder-Mead")
Error in pnorm(au_j, mean = b_j * R_m, sd = sigma_j) :
object 'au_j' not found
推荐答案
很难说出从哪里开始.
It is difficult to tell where to start on this.
正如@mac所说,您的代码很难阅读.它还包含错误.
As @mac said, your code is difficult to read. It also contains errors.
例如,如果您尝试使用sum[c(1,2)]
,则会出现错误:您应该使用sum(c(1,2))
.无论如何,您似乎把总和放在了错误的位置.您不能在向量上使用if
和else if
,而需要使用ifelse
.您没有什么可以阻止标准偏差变为负数.还有更多.
For example, if you try sum[c(1,2)]
you will get an error: you should use sum(c(1,2))
. In any case, you seem to be taking the sum in the wrong place. You cannot use if
and else if
on vectors, and need to use ifelse
. You have nothing to stop the standard deviation going negative. There is more.
以下代码运行无错误或警告.您仍然必须决定它是否满足您的要求.
The following code runs without errors or warnings. You will still have to decide whether it does what you want.
a <- data.frame( R_j = c(0.002,0.003,0.05,-0.01,-0.0009,0.09,0.01,0.0006),
R_m = c(0.026567295,0.009798475,0.008497274,0.012464578,
0.002896023,0.000879473,0.003194435,0.010281122) )
llik = function(x)
{
al_j=x[1]; au_j=x[2]; sigma_j=x[3]; b_j=x[4]
sum(
ifelse(a$R_j< 0, log(1/(2*pi*(sigma_j^2)))-
(1/(2*(sigma_j^2))*(a$R_j+al_j-b_j*a$R_m))^2,
ifelse(a$R_j>0 , log(1/(2*pi*(sigma_j^2)))-
(1/(2*(sigma_j^2))*(a$R_j+au_j-b_j*a$R_m))^2,
log(pnorm(au_j,mean=b_j*a$R_m,sd=sqrt(sigma_j^2))-
pnorm(au_j,mean=b_j*a$R_m,sd=sqrt(sigma_j^2)))))
)
}
start.par = c(0, 0, 0.01, 1)
out1 = optim(llik, par=start.par, method="Nelder-Mead")
这篇关于为什么我要估算的参数“未找到"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!