title: Where to define distribution function to be used with fitdist (fitdistrplus) or fitdistr (MASS)?
body: <p>I want to define my own distribution functions to be used with fitdist or fitdistr function in R. 
  Using fitdist in the fitdistrplus package as an example. I define a customized distribution called sgamma as follows:</p>
  
  <pre><code>dsgamma&lt;-function(x,shape){return(dgamma(x,shape,scale=1));}
  qsgamma&lt;-function(p,shape){return(qgamma(p,shape,scale=1));}
  psgamma&lt;-function(q,shape){return(pgamma(q,shape,scale=1));}
  rsgamma&lt;-function(n,shape){return(rgamma(n,shape,scale=1));}
  </code></pre>
  
  <p>My question is where I should define these functions. </p>
  
  <p>If the above definitnion and declaration is made in the top environment, then I could call fitdist using this distribution function. In other words, my script test1.R with the following content will run just fine:</p>
  
  <pre><code>rm(list=ls())
  require(fitdistrplus);
  dsgamma&lt;-function(x,shape){return(dgamma(x,shape,scale=1));}
  qsgamma&lt;-function(p,shape){return(qgamma(p,shape,scale=1));}
  psgamma&lt;-function(q,shape){return(pgamma(q,shape,scale=1));}
  rsgamma&lt;-function(n,shape){return(rgamma(n,shape,scale=1));}
  x&lt;-rgamma(100, shape=0.4, scale=1);
  zfit&lt;-fitdist(x, distr=dsgamma, start=list(shape=0.3));
  </code></pre>
  
  <p>Now, if I wrapped the above code in a function, it does not work. See test2.R below:</p>
  
  <pre><code>rm(list=ls())
  testfit&lt;-function(x)
  {
      require(fitdistrplus);
      dsgamma&lt;-function(x,shape){return(dgamma(x,shape,scale=1));}
      qsgamma&lt;-function(p,shape){return(qgamma(p,shape,scale=1));}
      psgamma&lt;-function(q,shape){return(pgamma(q,shape,scale=1));}
      rsgamma&lt;-function(n,shape){return(rgamma(n,shape,scale=1));}
      zfit&lt;-fitdist(x, distr=dsgamma, start=list(shape=0.3));
      return(zfit);
  }
  
  x&lt;-rgamma(100, shape=0.4, scale=1);
  zfit&lt;-testfit(x);
  </code></pre>
  
  <p>I got the following error:</p>
  
  <pre><code>Error in fitdist(x, distr = dsgamma, start = list(shape = 0.3)) : 
    The  dsgamma  function must be defined
  </code></pre>
  
  <p>Note that I still get an error if I replace</p>
  
  <pre><code>zfit&lt;-fitdist(x, distr=dsgamma, start=list(shape=0.3));
  </code></pre>
  
  <p>with</p>
  
  <pre><code>zfit&lt;-fitdist(x, distr="sgamma", start=list(shape=0.3));
  </code></pre>
  
  <p>I guess the key question is where fitdist look for the function specified by the parameter distr. I would really appreciate your help.</p>