0

我正在编写一个使用 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= "+"))) 

如果我的数据中有很多列,则公式并不总是得到公式化。我应该怎么做才能让它始终工作?我用+运算符连接所有列的名称。

4

1 回答 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)
}

我从我的 python 程序中使用rpy2. 这没有问题,因为每当我们使用这个公式时,我们都会将数据本身附加到它上面,所以它不会有问题。一个示例代码来演示我在说什么:

        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)

于 2020-02-29T13:47:59.250 回答