已封装为函数,
文件名 - PyPower.py
# 推荐使用conda管理环境
# conda create --name test python=3.6
# source activate test
# conda install rpy2 # should add conda-forge channel
# reference link: <http://www.cnblogs.com/cloudtj/articles/6372200.html>, <https://rpy2.readthedocs.io/en/version_2.8.x/index.html>
def pyPower_ttest(n='NULL', d='NULL', sig_level=0.05, power='NULL', type="two.sample", alternative='two.sided'):
'''
Compute power of tests or determine parameters to obtain target power. Exactly one of the parameters 'd','n','power' and 'sig_level' must be passed as 'NULL'. Results returned as a dictory.
This is an API function calling pwr.t.test function of R in Python using rpy2, pwr package (R environment) must be pre-installed.
Arguments:
n
Number of observations (per sample)
d
Effect size (Cohen's d) - difference between the means divided by the pooled standard deviation
sig_level
Significance level (Type I error probability)
power
Power of test (1 minus Type II error probability)
type
Type of t test : one- two- or paired-samples
alternative
a character string specifying the alternative hypothesis, must be one of "two.sided" (default), "greater" or "less"
Example:
from PyPower import pyPower_ttest
pyPower_ttest(d=0.2,n=60,sig_level=0.10,type="one.sample",alternative="two.sided")
pyPower_ttest(d=2/2.8,n=30,sig_level=0.05,type="two.sample",alternative="two.sided")
pyPower_ttest(d=0.3,power=0.75,sig_level=0.05,type="two.sample",alternative="greater")
Note:
More information please run ?pwr::pwr.t.test in R console
'''
# 载入r对象
from rpy2 import robjects
# 载入导入包函数
from rpy2.robjects.packages import importr
# 将pwr包导入为模块,记得提前在(test环境下)R中安装好pwr包
pwr = importr('pwr')
# When one wants to create a vector from Python, either the class Vector or the convenience classes IntVector, FloatVector, BoolVector, StrVector can be used.
# 将参数中的.替换为_,解决不兼容问题, 来自rpy2文档函数部分
# rpy2默认支持该转换,可以删除该部分以简化代码
def iamfeelinglucky(func):
def f(*args, **kwargs):
d = {}
for k, v in kwargs.items():
d[k.replace('_', '.')] = v
return func(**d)
return f
# 矫正参数名
power_ttest = iamfeelinglucky(pwr.pwr_t_test)
# 重命名r中的as.null函数,用于将字符'NULL'转换为NULL对象
as_null = robjects.r['as.null']
# 转换
args_list = [n, d, sig_level, power]
for i,v in enumerate(args_list):
if v == "NULL":
args_list[i] = as_null(v)
# 调用函数
pwr_res = power_ttest(n=args_list[0], d=args_list[1], sig_level=args_list[2], power=args_list[3], type=type, alternative=alternative)
# 输出分析结果
print(pwr_res)
res = list(pwr_res)
# 返回结果中需要的值构建字典
res = {'n':res[0], 'd':res[1], 'sig_level':res[2], 'power':res[3], 'alternative':res[4], 'method':res[6]}
# 返回的是robject对象,再转换为标准的python对象
res['n'] = list(res['n'])[0]
res['d'] = list(res['d'])[0]
res['sig_level'] = list(res['sig_level'])[0]
res['power'] = list(res['power'])[0]
res['alternative'] = list(res['alternative'])[0]
res['method'] = list(res['method'])[0]
return(res)