我正在尝试使用Subprocess库从Python运行R代码。我需要从python运行一个.R文件,并传递一个字符串值(args = [“ INV28338”])。我是R语言的新手,因此无法在R和Python中找出确切的数据类型转换代码。
[请有人帮我,如何将单个字符串/标量值从Python传递给R函数/模型?稍后,我将为该代码提供“ Flask REST API”的形状。
非常感谢您
import subprocess
command = 'Rscript'
path2script = 'classification_model_code.R'
args = ["INV28338"]
cmd = [command, path2script] + args
x = subprocess.check_output(cmd, universal_newlines=True)
print('The Output is:', x)
myArgs <- commandArgs(trailingOnly = TRUE)
nums = as.numeric(myArgs)
invoice_in_scope<-nums
#Followed by more code
我的脚本,test2.R
myArgs <- commandArgs(trailingOnly = TRUE)
nums = as.numeric(myArgs)
print(nums)
您需要将args
作为列表的一部分,因此将其附加到cmd
上就可以了:
import subprocess
command = 'Rscript'
path2script = './test2.R'
args = "9"
cmd = [command, path2script]
cmd.append(args)
x = subprocess.check_output(cmd, universal_newlines=True)
print('The Output is:', x)