2017-03-16 22 views
1

私は複数のRスクリプトを呼び出すPythonスクリプトを持っていますが、これまでは1つの変数と複数の変数を渡して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 

答えて

2

あなたはフラットなリストを生成するためにa_list[r_path, script]を連結する必要があります。

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

REPL

script.R

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

Pythonは美しく働きました。私は 'subprocess.call()'のリスト構文については考えていませんでした。 – cptpython

関連する問題