R script on Jupyter notebook
Usually, Jupyter notebooks are using only one language at once: The one by the kernel (Python in your case).
You can use Script of Scripts (SoS) to make Jupyter polyglot to handle both python and R code in one Notebook. There is also reticulate and rpy2 to mix python and R code.
To show R results in Jupyter notebook, I recommend to export the R results in a language agnostic file format e.g. csv or json. These files can be easily imported in python afterwards.
Share variables between R and Python in jupyternotebook
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.
Related Topics
Is Shared Readonly Data Copied to Different Processes for Multiprocessing
Authenticate from Linux to Windows SQL Server with Pyodbc
Detecting When a Child Process Is Waiting for Input
Why Is a List Comprehension So Much Faster Than Appending to a List
Error: Command 'Gcc' Failed with Exit Status 1 While Installing Eventlet
How to Get the Path of the Python Script I am Running In
Detecting Consecutive Integers in a List
How to Make a Single Legend for Many Subplots with Matplotlib
Return in Generator Together with Yield
Keyboard Interrupts with Python's Multiprocessing Pool
Python3.6 Importerror: Cannot Import Name 'Main' Linux Rhel6
How Is the 'Is' Keyword Implemented in Python
Scraping: Ssl: Certificate_Verify_Failed Error for Http://En.Wikipedia.Org
Error: (-215) !Empty() in Function Detectmultiscale
Python's Most Efficient Way to Choose Longest String in List