如何从python向Rscript传递整数参数

2024-04-18 00:59:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经发布了下面的R代码,我想从python代码中传递参数n,并显示结果。也就是说,如果我通过了4,那么16必须在屏幕上打印出来。 请让我知道如何将argumnets从python传递到R-script

R代码

Square <- function(n) {
return(n^2)
}

Python代码

command ='Rscript'
path2Func1Script ='/var/www/aw/Rcodes/func-1.R'
args = [3]
cmd = [command, path2Func1Script]

output = None
try:
    x = subprocess.call(cmd + args, shell=True)
    print("x: ", x)
except subprocess.CalledProcessError as e:
    output = e.output
    print("output: ", output)

Tags: 代码cmdoutput参数return屏幕scriptargs
1条回答
网友
1楼 · 发布于 2024-04-18 00:59:21

解决方案:

我看到您正在手动执行此操作。我建议您使用为此构建的很棒的python库rpy2Rpy2提供了许多使用python本身的R库和函数的功能,而无需使用子流程从python手动调用命令行参数中的r脚本,这不仅使编写代码更容易,而且效率更高

需要注意的最重要的一点是,要将python整数列表解析为r函数,您需要将其转换为r IntVector,如robjects.vectors.IntVector()。另一件需要提及的是,如果您使用windows,则需要将R_HOME环境变量设置为r安装的路径

首先使用conda安装rpy2pip仅适用于带有此软件包的linux):

conda install -c conda-forge rpy2

以下是python代码:

import rpy2.robjects as robjects


# Defining the R script and loading the instance in Python
r = robjects.r
r['source']('func-1.R')

# Loading the function we have defined in R.
square_func = robjects.globalenv['Square']

# defining the args
args = robjects.vectors.IntVector([3])

#Invoking the R function and getting the result
result_r = square_func(args)

#printing it.
print('x: ' , result_r)

输出:

x: [1] 9

相关问题 更多 >

    热门问题