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.