title: R - fit histogram: peaked signal plus background
body: <p>I need to fit with R an histogram containing a peaked signal plus a flat background. Like these:</p>
  
  <p><a href="https://www.google.it/search?q=signal+plus+background&amp;espv=2&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ei=Tz6xU8zTJ_Pb7Ab74YCwCA&amp;ved=0CAYQ_AUoAQ&amp;biw=1280&amp;bih=920#facrc=_&amp;imgdii=_&amp;imgrc=uEPi2KWaZEaaRM%253A%3B9wYKcWTJ0ARIuM%3Bhttp%253A%252F%252Fwwwasd.web.cern.ch%252Fwwwasd%252Fpaw%252Fcontributions%252Fbwp4_fit.gif%3Bhttp%253A%252F%252Fwwwasd.web.cern.ch%252Fwwwasd%252Fpaw%252Fcontributions%252Ffit_kumac_examples.html%3B529%3B483" rel="nofollow noreferrer">Google Images Link</a> to:</p>
  
  <p><a href="http://wwwasd.web.cern.ch/wwwasd/paw/contributions/bwp4_fit.gif" rel="nofollow noreferrer">pic http://wwwasd.web.cern.ch/wwwasd/paw/contributions/bwp4_fit.gif</a></p>
  
  <p>How can I do efficiently in R? I haven't found any good reference on the web.
  I was used to do this in ROOT: <a href="http://root.cern.ch/root/html/tutorials/fit/FittingDemo.C.html" rel="nofollow noreferrer">http://root.cern.ch/root/html/tutorials/fit/FittingDemo.C.html</a>
  but in R it's not so easy...</p>
  
  <p>I did something using fitdistr (MASS package), but it woks well only if I use a single given distribution (e.g. a gaussian).
  If I try to add to the gaussian a flat (uniform) background, adding a parameter for the relative presence of the two distributions:</p>
  
  <pre><code>f = gaus(mean, sigma) + r * uniform
  </code></pre>
  
  <p>with mean, sigma and r free parameters, the fit doesn't work anymore.</p>
  
  <p>Typical errors are:</p>
  
  <pre><code>Error in solve.default(res$hessian) : 
    Lapack routine dgesv: system is exactly singular: U[1,1] = 0
  In addition: There were 28 warnings (use warnings() to see them)
  </code></pre>
  
  <p>or simply there's no convergence.</p>
  
  <p>Finally, I don't understand how R deals with normalization constants (multiplicative parameters in front of each added distribution). I guess that if we fit the frequencies everything (histogram and fit curve) should be already normalized to unity.. By consequence the only new parameter when adding a flat background to the peaked signal should be the relative weight (r in the above example). Is this the case?</p>
  
  <p>Thanks
  Marco</p>