7

I'm new to Jupyter notebook and I'm trying to set one up with Python and R, using rpy2. I have the line

%%R -i df

which gives me the error SyntaxError: invalid syntax

However when I use just one %, such as

%R require(ggplot2)

this works fine. How can I fix this issue? I am using Python 2.7.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
Lawrence Pang
  • 207
  • 1
  • 3
  • 5

2 Answers2

5

% prefix is for a line magic, whereas %% prefix is for a cell magic.

%%R    # <-- must be the only instruction on this line
{body of cell in R code}

whereas:

%R {one line of R code}

I don't have R installed, but I think you may have wanted to call a bash command on R; in that case, use ! to call the command:

!R -i df

for instance, if I type !python -i, I get info about my current python environment:

Python 3.6.2 |Anaconda custom (x86_64)| (default, Jul 20 2017, 13:14:59) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
3

This is an old question but I run into the same problem today. Reblochon Masque's answer no longer applies as of today. %%R -i df in the middle of a cell throws invalid syntax. Also !R -i df throws WARNING: unknown option '-i' ARGUMENT 'df' __ignored__.

Here is what I need to do to cell magic R to work:

  1. follow this instruction to install R packages RJSONIO and httr (package name is indeed lowercase) and Python package rpy2. No further configuration is needed.

  2. put just one line %load_ext rpy2.ipython in a cell to invoke rpy2.

  3. %%R has to be at the very beginning of a cell, so I put this line in the next cell.

  4. the body of cell cannot be empty after %%R.

  5. %%R -i df does work as intended.

Alex
  • 33
  • 8