3

I have a python script that calls to multiple R scripts, so far I can successfully pass single and multiple variables, ask R to read and execute it. My current method is very crude and it is only effective when passing strings and fails with numbers. Is there an efficient way to accomplish this task?

#### 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 Answer 1

5

You should concatenate [r_path, script] with a_list to produce a flat 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"
Sign up to request clarification or add additional context in comments.

1 Comment

Worked beautifully. I didn't even think about the list syntax for the subprocess.call().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.