gpt4 book ai didi

python - 将多个参数从 python 传递到 R

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:47 24 4
gpt4 key购买 nike

我有一个调用多个 R 脚本的 python 脚本,到目前为止我可以成功传递单个和多个变量,让 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

最佳答案

您应该将 [r_path, script]a_list 连接起来以生成平面列表。

脚本.R

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

Python 回复

>>> 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"

关于python - 将多个参数从 python 传递到 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42823590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com