我想定义自己的分布函数,与 R 中的 fitdist 或 fitdistr 函数一起使用。
以 fitdistrplus 包中的 fitdist 为例。我定义了一个名为 sgamma 的自定义分布,如下所示:
dsgamma<-function(x,shape){return(dgamma(x,shape,scale=1));}
qsgamma<-function(p,shape){return(qgamma(p,shape,scale=1));}
psgamma<-function(q,shape){return(pgamma(q,shape,scale=1));}
rsgamma<-function(n,shape){return(rgamma(n,shape,scale=1));}
我的问题是我应该在哪里定义这些函数。
如果上面的定义和声明是在顶层环境中进行的,那么我可以使用这个分布函数调用 fitdist 。换句话说,我的脚本 test1.R 包含以下内容将运行得很好:
rm(list=ls())
require(fitdistrplus);
dsgamma<-function(x,shape){return(dgamma(x,shape,scale=1));}
qsgamma<-function(p,shape){return(qgamma(p,shape,scale=1));}
psgamma<-function(q,shape){return(pgamma(q,shape,scale=1));}
rsgamma<-function(n,shape){return(rgamma(n,shape,scale=1));}
x<-rgamma(100, shape=0.4, scale=1);
zfit<-fitdist(x, distr=dsgamma, start=list(shape=0.3));
现在,如果我将上面的代码包装在一个函数中,它就不起作用了。参见下面的test2.R:
rm(list=ls())
testfit<-function(x)
{
require(fitdistrplus);
dsgamma<-function(x,shape){return(dgamma(x,shape,scale=1));}
qsgamma<-function(p,shape){return(qgamma(p,shape,scale=1));}
psgamma<-function(q,shape){return(pgamma(q,shape,scale=1));}
rsgamma<-function(n,shape){return(rgamma(n,shape,scale=1));}
zfit<-fitdist(x, distr=dsgamma, start=list(shape=0.3));
return(zfit);
}
x<-rgamma(100, shape=0.4, scale=1);
zfit<-testfit(x);
我收到以下错误:
Error in fitdist(x, distr = dsgamma, start = list(shape = 0.3)) :
The dsgamma function must be defined
请注意,如果我替换,我仍然会收到错误
zfit<-fitdist(x, distr=dsgamma, start=list(shape=0.3));
with
zfit<-fitdist(x, distr="sgamma", start=list(shape=0.3));
我想关键问题是 fitdist 在哪里寻找参数 distr 指定的函数。我将衷心感谢您的帮助。