[R] Fitting and Plotting the fitted distributions

Rui Barradas ruipbarradas at sapo.pt
Tue Jul 3 10:23:08 CEST 2012


Hello,

This is here for some days now, and I've decided to give it a try.

I've rewritten your fitfunction(), making it simpler. And include the 
gamma distribution in the list.



require(MASS)

fitfunction <- function(Type, x) list(Type=Type, Fit=fitdistr(x, Type))

fun <- function(x, data){
	data <- sort(data)
	if(x$Type == "exponential")
		y <- pexp(data, rate=x$Fit$estimate['rate'])
	else if(x$Type == "geometric")
		y <- pgeom(data, prob=x$Fit$estimate['prob'])
	else if(x$Type == "log-normal")
		y <- plnorm(data, meanlog=x$Fit$estimate['meanlog'], 
sdlog=x$Fit$estimate['sdlog'])
	else if(x$Type == "normal")
		y <- pnorm(data, mean=x$Fit$estimate['mean'], sd=x$Fit$estimate['sd'])
	else if(x$Type == "Poisson")
		y <- ppois(data, lambda=x$Fit$estimate['lambda'])
	else if(x$Type == "gamma")
		y <- pgamma(data, shape=x$Fit$estimate['shape'], 
rate=x$Fit$estimate['rate'])
	list(x=data, y=y)
}


set.seed(1)

distrList <- list("exponential", "geometric", "log-normal", "normal", 
"Poisson", "gamma")

On <- round(abs(rnorm(10000, sd=100))+5,digits=0)

storeOn <- lapply(distrList, fitfunction, x=On)
str(storeOn)
lapply(storeOn, function(x) AIC(x$Fit))

coord <- lapply(storeOn, fun, On)
color <- seq_along(distrList) + 1

plot(ecdf(On), verticals= TRUE, do.p = FALSE, lwd=2)
lapply(seq_along(coord), function(i)
	lines(coord[[i]]$x, coord[[i]]$y, col=color[i]))
legend("right", legend=distrList, col=color, lty=1, bty="n")


Hope this helps,

Rui Barradas

Em 02-07-2012 07:13, Alaios escreveu:
> Dear all,
> I have wrote some sample code that would allow me easier fit fast many distributions and check which of the fits performs better. My sample code (that you can of course execute it looks like that)
>
>
> distrList<-list(   "exponential",  "geometric", "log-normal",  "normal",
> "Poisson")
>
>
>
> fitfunction<-function(Type,x){
>      return (list(Type,(fitdistr(x,Type))))
> }
>
> require(MASS)
> On<-round(abs(rnorm(10000,sd=100))+5,digits=0)
>
> storeOn<-lapply(distrList,fitdistr,x=On)
> plot(ecdf(On))
> str(storeOn)
>
>
> what I am looking now is to plot with the initial dataset plot(ecdf(On)) all the fitted distributions over the same window.
> I am not sure though, if there is some straightforward way (i.e same random distribution generator) for the fitted paramemeters to plot those over the existing
> plot(ecdf(On)).
>
> Could you please help me with that?
>
> Regards
> Alex
>
> 	[[alternative HTML version deleted]]
>
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list