Interfacing R via magic command

Qianjiang Hu     2021-02-25

There is a lot of interest and debate over what is the best language for data science between R and Python. Sine, both of them present advantages and disadvantages, why don't we use both? Fortunately, Ipython and rpy2 offer an interactive environment via Rmagic.

Enable the interactive R magic

Enable the R magic by executing %load_ext rpy2.ipython, not necessary if you have done this. (need to install rpy2 firstly)

Line and Cell magics

In general, %R is the line magic, executing R magic in the line; while %%R is the cell magics, executing R magic in a block.

optional arguments:

-i     INPUT
Objects that will be loaded into R kernel from Python Kernel.
Multiple object names can be loaded, separated by commas with no whitespace.

-o     OUTPUT
Names of variables that will be export to Python Kernel from R kernel.
Multiple object names can be exported, separated by commas with no whitespace.

-n     NORETURN
Force the magic to not return anything.

-w    WIDTH
Width of plotting device in R.

-h    HEIGHT
Height of plotting device in R.

-p    POINTSIZE
Pointsize of plotting device in R.

-b    BG
Background of plotting device in R.

alternatives for -i and -o

%Rpush and %Rpull are the alternatives of -i and -o respectively.

%Rpush

%Rpush all objects followed will be loaded into R kernel from Python Kernel.
Multiple object names can be loaded, separated by whitespace.

%Rpull

%Rpull all objects followed will be export to Python Kernel from R kernel.
Multiple object names can be exported, separated by whitespace

plots

Reference

https://rpy2.github.io/doc/latest/html/interactive.html

Supplement

%lsmagic
List currently available magic functions.

%magic_name?
check the documents of specific magic command