user44796
user44796

Reputation: 1219

Pass variable into python script from R using system2()

I have seen various versions of this question, but have not been able to figure out how to pass numeric variables into Python from R using system2()

For example suppose I have the following python script as Test.py.

a = 1
b = 2
def add(a,b):
    print a + b

I can run this in R with

pypath = './Test.py'
system2('python', args=(sprintf('"%1$s"',pypath)))

but what if I wanted to pass the values of a and b in, and have the values returned within R to an R object? Something like,

a = 1
b = 2
d = system2('python',args = (sprintf('"%1$s" "%2$s" "%3$s"',pypath,a,b)))

I have tried a variety of ways of doing this, but have failed. I know the above is wrong, I just can't figure out how to pass in a and b, much less return a value

My questions are (1) is it possible? and (2) how do you do it?

Upvotes: 0

Views: 1420

Answers (2)

OganM
OganM

Reputation: 2663

System2 takes in an array of characters. So instead of trying to feed an entire string, you can just do

system2('python', args = c('./Test.py', as.character(a), as.character(b)))

One way of transferring the output to R is to use ">" to write it to a file then reading the file from R. (I'm sure this isn't the most efficient way to do this).

system2('python',args = c('/Test.py', as.character(a), as.character(b), '>/targetDir/targetFile'))

Upvotes: 3

cory
cory

Reputation: 6659

I've always just concatenated my whole string together...

a <- "/path/to/python"
b <- "script_to_call.py"
c <- 1

system(paste0(a, " ", b, " ", c))

Upvotes: 1

Related Questions