【问题标题】:How to pass integer arguments to R-script from python如何从python将整数参数传递给R脚本
【发布时间】:2021-07-14 08:30:59
【问题描述】:

我有下面发布的 R 代码,我想从 python 代码传递参数n并显示结果。也就是说,如果我通过了 4,那么 16 必须在屏幕上打印出来。 请让我知道如何从 python 将 argumnets 传递给 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)

【问题讨论】:

  • 您可以在问题中添加您正在使用的python版本吗?
  • 嗨@Letsamrit,我已经进行了进一步的测试和研究,并确保我的答案能回答所有问题,希望对您有所帮助

标签: python r


【解决方案1】:

解决方案:

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

需要注意的最重要的一点是,要将 python 整数列表解析为 r 函数,您需要将其转换为 r IntVector,就像 robjects.vectors.IntVector() 一样。另外要提到的是,您需要设置 @987654328 @ 环境变量指向你的 R 安装路径,如果你使用的是 windows 的话

首先使用 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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 2010-10-26
  • 2019-12-20
相关资源
最近更新 更多