将多个参数从Python传递到R

3

我有一个Python脚本,需要调用多个R脚本。目前我可以成功地传递单个和多个变量,并让R读取和执行它们。但我目前的方法非常简陋,只能在传递字符串时生效,数字则失败。是否有更有效的方法来完成这个任务?

#### Python Code
import subprocess

def rscript():
    r_path = "C:/.../R/R-3.3.2/bin/x64/Rscript"
    script = "C:/.../test.R" 

    #The separators are not recognized in R script so commas are added for splitting text
    a_list = ["C:/SomeFolder,", "abc,", "25"] 

    subprocess.call ([r_path, script, a_list], shell = True)
    print 'Script Complete'

#Execute R Function
rscript()

#### R Code
options(echo=TRUE)
args <- commandArgs(trailingOnly = TRUE)

print(args)

args1 <- strsplit(args,",") #split the string argument with ','
args1 <- as.data.frame(args1)

print(args1)

path <- as.character(args1[1,])
abc <- as.character(args1[2,])
number <- as.numeric(args1[3,])

print (path)
print (abc)
print (number)

write.table(path, file = "C:/path.txt", row.names = FALSE)
write.table(abc, file = "C:/abc.txt", row.names = FALSE)
write.table(number, file = "C:/number.txt", row.names = FALSE)

#### R - Output
> print (path)
[1] "C:/SomeFolder"
> print (abc)
[1] "abc"
> print (number)
[1] 1
1个回答

5
你应该将[r_path, script]a_list连接起来,以生成一个扁平的列表。

script.R

options(echo=TRUE)
args <- commandArgs(trailingOnly = TRUE)
print(args)

Python repl

>>> commands = ["rscript", "script.R"]
>>> args = ["C:/SomeFolder", "abc", "25"]
>>> subprocess.call(commands + args, shell=True)
> args <- commandArgs(trailingOnly = TRUE)
>
> print(args)
[1] "C:/SomeFolder" "abc"           "25"

运行得非常好。我甚至没有考虑过subprocess.call()的列表语法。 - cptpython

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接