import rpy2.robjects as R
import rpy2.robjects.packages as R_packages
R_test, R_mass = R.packages.importr('goftest'), R.packages.importr('MASS')
R_ksr_test, R_ad_test, R_chisq_test = R.r['ks.test'], R.r['ad.test'], R.r['chisq.test']
distributions = [('norm', 'normal'), # mean, deviation
('pexp', 'exponential'), # rate
('pweibull', 'weibull') # shape, scale
]
def make_test(data, distribution, conf, test='ad'):
args = {}
dist, name = distribution
if name in mean_param: args['mean'] = conf['mean']
if name in sd_param: args['sd'] = conf['sd']
if name in shape_param: args['shape'] = conf['shape']
if name in scale_param: args['scale'] = conf['scale']
if name in rate_param: args['rate'] = conf['rate']
if test == 'ks':
return R_ksr_test(data, dist, **args)
elif test == 'chi2':
return R_chisq_test(data, dist, **args)
return R_ad_test(data, dist, **args)
def get_fitdistr(items, distribution):
data = {}
response = R_mass.fitdistr(items, distribution)
if distribution == 'weibull':
data['shape'], data['scale'] = response[0]
elif distribution == 'exponential':
data['rate'] = response[0][0]
else:
data['mean'], data['sd'] = response[0]
return data
vector = [9.2, 10.5, 10.8, 12.3, 14.8, 15.6, 16.1, 19.5, 22.4, 24.7, 25.3, 26.5, 29.9, 30.3, 30.7, 35.6, 46.5, 50.4, 68.2, 90.6]
vector = R.IntVector(vector)
data = u.get_fitdistr(vector, distributions[2][1])
stat, p_val, method, name = u.make_test(vector, distributions[2], data)
As you can see I am calling ad.test, ks.test and chisq.test without problems, but I need to offer the choice of change the significance level in each test.