0

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?

5
  • Yes it's possible. But before you start with this, I think it would benefit to take a look at IPython, which was built pretty much for such integration purposes Commented May 20, 2015 at 19:05
  • Passing a and b is easy. You don't even need to use sptintf as you are doing right now. args argument takes in an array of characters so it you just to system2('python', args = c('./Test.py', as.character(a), as.character(b))). To write into a file, as a workaround you can use > to direct the output to a temp file and read from the file with R. It'll be slower but it'll work Commented May 20, 2015 at 19:09
  • Thanks @OganM. That is exactly what I was looking for. How do I use > to direct the output to a file using system2()? I have seen it used it with system, but not system2(). Commented May 20, 2015 at 19:26
  • just add it as another argument. system2('yourcommand',c('ARG1', 'ARG2', '>/targetDir/targetFile')) Commented May 20, 2015 at 19:49
  • If you add this as the answer, I can upvote it. Commented May 20, 2015 at 19:51

2 Answers 2

3

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'))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.