[R] Help with R Fitting an inverse Gamma
kmammasis
mammasis82 at hotmail.com
Thu Oct 4 12:42:37 CEST 2012
Dear all,
I am new in R and would like to ask for someone's help in understanding
where I go wrong with the following code:
rm(list=ls())
# Required packages
library(MCMCpack)
# Simulated data
set.seed(1)
data = rinvgamma(n=250, shape = 5, scale = 2) + 2
hist(data)
# log-likelihood
ll = function(par){
if(par[1]>0 & par[2]>0 & par[3]<min(data)) return( -sum(log(dinvgamma(data-
par[3],par[1],par[2]))) )
else return(Inf)
}
# MLE
mle = optim(c(5,2,2),ll)
params = mle$par
# Fit
hist(data,probability=T,ylim=c(0,2.5))
points(seq(2,4.5,0.001),dinvgamma(seq(2,4.5,0.001)-params[3],params[1],params[2]),type="l",col="red")
This code fits an Inverse Gamma distribution to the randomly generated data
and plots the associated histogram. My problem is that when I try to import
a dataset saved locally it gives me an error. Here is the modification of
the code:
# Required packages
library(MCMCpack)
data=my.csv.data$V1
hist(data)
# log-likelihood
ll = function(par){
if(par[1]>0 & par[2]>0 & par[3]<min(data)) return( -sum(log(dinvgamma(data-
par[3],par[1],par[2]))) )
else return(Inf)
}
# MLE
mle = optim(c(5,2,2),ll)
params = mle$par
# Fit
hist(data,probability=T,ylim=c(0,2.5))
points(seq(2,4.5,0.001),dinvgamma(seq(2,4.5,0.001)-params[3],params[1],params[2]),type="l",col="red")
I have attached the file which I import directly from the menu, named:
excel250.csv. When I run the code it gives me the following error:
Error in optim(c(5, 2, 2), ll) :
function cannot be evaluated at initial parameters
I would appreciate your help.
Thank you.
Konstantinos
<nabble_a href="excel250.csv">excel250.csv
--
View this message in context: http://r.789695.n4.nabble.com/Help-with-R-Fitting-an-inverse-Gamma-tp4644984.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list