Fitting distribution by combing R and Python

The following example illustrates how to use R package with Python by using the Rpy2 package.
This problem solve in this example is to fit a normal distribution on some data samples.

from rpy2.robjects import r
from rpy2.robjects.packages import importr
rnorm = r('rnorm')  # create an alias to the R function rnorm
x = rnorm(n=1000, mean=0, sd=1) # generates the data sample (normal distribution)
# load the MASS library for distribution fitting
MASS = importr('MASS')
params = MASS.fitdistr(x, 'normal')  # perform the fitting here
print params

The result is stored in the variable params. The above code print the following results:

      mean           sd     
  -0.07962739    1.00467570 
 ( 0.03177064) ( 0.02246523)

Telling you that the distribution has mean of -0.08 and a standard deviation of 0. The bracketted numbers indicates how trustful are the results. Numbers in parentheses are confidence intervals around the parameter.

Please follow and like us:
This entry was posted in Python and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *