在python中調(diào)用R的pwr功效函數(shù)

已封裝為函數(shù),

文件名 - PyPower.py

# 推薦使用conda管理環(huán)境
# 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
    # 載入導(dǎo)入包函數(shù)
    from rpy2.robjects.packages import importr
    # 將pwr包導(dǎo)入為模塊,記得提前在(test環(huán)境下)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.
    
    # 將參數(shù)中的.替換為_,解決不兼容問題, 來自rpy2文檔函數(shù)部分
    # rpy2默認(rèn)支持該轉(zhuǎn)換,可以刪除該部分以簡化代碼
    def iamfeelinglucky(func):
        def f(*args, **kwargs):
            d = {}
            for k, v in kwargs.items():
                d[k.replace('_', '.')] = v
            return func(**d)
        return f

    # 矯正參數(shù)名
    power_ttest = iamfeelinglucky(pwr.pwr_t_test)

    # 重命名r中的as.null函數(shù),用于將字符'NULL'轉(zhuǎn)換為NULL對象
    as_null = robjects.r['as.null']
    # 轉(zhuǎn)換
    args_list = [n, d, sig_level, power]
    for i,v in enumerate(args_list):
        if v == "NULL":
            args_list[i] = as_null(v)

    # 調(diào)用函數(shù)
    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)

    # 輸出分析結(jié)果       
    print(pwr_res)
    res = list(pwr_res)
    # 返回結(jié)果中需要的值構(gòu)建字典
    res = {'n':res[0], 'd':res[1], 'sig_level':res[2], 'power':res[3], 'alternative':res[4], 'method':res[6]}
    # 返回的是robject對象,再轉(zhuǎn)換為標(biāo)準(zhǔn)的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)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容