5

How to pass the R variable to Python?

In jupyternotebook, I'm using %reload_ext rpy2.ipython to use R and Python in one note. I know how to pass python variable to R by using %%R -i xxx to pass a python variable xxx to R in the cell, but how to pass a R variable back to python? It's it possible technically?

swatchai
  • 17,400
  • 3
  • 39
  • 58
Kid
  • 413
  • 4
  • 11

1 Answers1

6

The following Jupyter magic code demonstrates the use of R to compute 1+2+3 and save the result in variable rvar, then pass it to Python. The option -o rvar specifies that the variable rvar is required as output to Python environment.

%R -o rvar rvar=1+2+3

On another cell, you can use Python to manipulate that variable:

print(rvar)      # [1] 6
print(rvar[0])   # 6.0

For more complex example, with multiple output variables:

%%R -o X -o sdx -o xbar
X=c(1,4,5,7);
sdx=sd(X);
xbar=mean(X)

In (Python) Jupyter notebook, you get X, sdx, and xbar as the output. You can check them by running the code:

print('X:', X)
print('X[1]:', X[1])
print('sdx:', sdx)
print('xbar:', xbar)

More information about R magic can be found here.

Alternatively, you can use %Rpull and %Rget to get object from rpy2.

Edit

Updated reference link as hinted by @lgautier in the comment.

swatchai
  • 17,400
  • 3
  • 39
  • 58
  • Thank you so much for your answer, and I'm wondering where did you see these instructions about this? And how should I output multiple variables in one block? Thanks for your patience – Kid Apr 26 '19 at 01:11
  • 1
    @swatchai: that documentation is long outdated, as the "R magic" moved out of the ipython code base. You might want use https://rpy2.github.io/doc/v3.0.x/html/interactive.html#module-rpy2.ipython.rmagic as your reference documentation instead. – lgautier Apr 28 '19 at 17:25
  • is it possible to do the reverse ? using Python variables in R ? – Shidharth Routh Apr 19 '22 at 04:32
  • 1
    @ShidharthRouth Objects can be passed back and forth between rpy2 and python via the -i -o flags in line. See https://rpy2.github.io/doc/v3.0.x/html/interactive.html#module-rpy2.ipython.rmagic for examples. – swatchai Apr 19 '22 at 07:57
  • thank you. I was able to figure it out after dabbling with it. – Shidharth Routh Apr 19 '22 at 10:46