使用Python创建R的公式

问题描述 投票:0回答:1

我正在编写一个使用Python与R交互的程序。基本上,我有一些R库要提取到我的Python代码中。下载rpy2之后,我定义了我想在单独的.R文件脚本中使用的R函数。

R函数要求我们将公式传递给它,以便应用某些oversampling技术。下面是我写的R函数:

WFRandUnder <- function(target_variable, other, train, rel, thr.rel, C.perc, repl){
    a <- target_variable
    b <- '~'
    form_begin <- paste(a, b, sep=' ')
    fmla <- as.formula(paste(form_begin, paste(other, collapse= "+")))
    undersampled = RandUnderRegress(fmla, train, rel, thr.rel, C.perc, repl)
    return(undersampled)
}

我正在从python传递目标变量名称,以及一个包含所有其他列名称的列表。我希望它如下:my_target_variable ~ all other columns

但是在这些行中:

a <- target_variable
    b <- '~'
    form_begin <- paste(a, b, sep=' ')
    fmla <- as.formula(paste(form_begin, paste(other, collapse= "+"))) 

如果我的数据中有很多列,则公式不一定总是公式化的。我应该怎么做才能使其始终正常工作?我正在用+运算符连接所有列的名称。

python r formula rpy2 oversampling
1个回答
0
投票

感谢@nicola,通过执行以下操作,我能够解决此问题:

create_formula <- function(target_variable, other){
    # y <- target_variable
    # tilda <- '~'
    # form_begin <- paste(y, tilda, sep=' ')
    # fmla <- as.formula(paste(form_begin, paste(other, collapse= "+")))
    # return(fmla)
    y <- target_variable
    fmla = as.formula(paste(y, '~ .'))
    return(fmla)
}

我使用rpy2从我的python程序中调用此函数。这没有问题,因为无论何时使用此公式,我们都会将数据本身附加到它,因此它不会有问题。示例代码演示我在说什么:

        if self.smogn:
            smogned = runit.WFDIBS(

                 # here is the formula call (get_formula is a python function that calls create_formula defined above in R)
                fmla=get_formula(self.target_variable, self.other),

                # here is the data 
                dat=df_combined,

                method=self.phi_params['method'][0],
                npts=self.phi_params['npts'][0],
                controlpts=self.phi_params['control.pts'],
                thrrel=self.thr_rel,
                Cperc=self.Cperc,
                k=self.k,
                repl=self.repl,
                dist=self.dist,
                p=self.p,
                pert=self.pert)

© www.soinside.com 2019 - 2024. All rights reserved.