简体   繁体   中英

Share variables between R and Python in jupyternotebook

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM