In [ ]:

```
%pylab inline
```

`rmagic`

extension that contains a some magic functions for working with R via rpy2. This extension can be loaded using the `%load_ext`

magic as follows:

In [1]:

```
%load_ext rmagic
```

In [2]:

```
import numpy as np
import pylab
X = np.array([0,1,2,3,4])
Y = np.array([3,5,4,6,7])
pylab.scatter(X, Y)
```

Out[2]:

In [3]:

```
%Rpush X Y
%R lm(Y~X)$coef
```

Out[3]:

We can check that this is correct fairly easily:

In [4]:

```
Xr = X - X.mean(); Yr = Y - Y.mean()
slope = (Xr*Yr).sum() / (Xr**2).sum()
intercept = Y.mean() - X.mean() * slope
(intercept, slope)
```

Out[4]:

It is also possible to return more than one value with %R.

In [5]:

```
%R resid(lm(Y~X)); coef(lm(X~Y))
```

Out[5]:

*coef(lm(X~Y))*. To pull other variables from R, there is one more magic.

In [6]:

```
b = %R a=resid(lm(Y~X))
%Rpull a
print a
assert id(b.data) == id(a.data)
%R -o a
```

%Rpull is equivalent to calling %R with just -o

In [7]:

```
%R d=resid(lm(Y~X)); e=coef(lm(Y~X))
%R -o d -o e
%Rpull e
print d
print e
import numpy as np
np.testing.assert_almost_equal(d, a)
```

On the other hand %Rpush is equivalent to calling %R with just -i and no trailing code.

In [8]:

```
A = np.arange(20)
%R -i A
%R mean(A)
```

Out[8]:

The magic %Rget retrieves one variable from R.

In [9]:

```
%Rget A
```

Out[9]:

In [10]:

```
v1 = %R plot(X,Y); print(summary(lm(Y~X))); vv=mean(X)*mean(Y)
print 'v1 is:', v1
v2 = %R mean(X)*mean(Y)
print 'v2 is:', v2
```

In [11]:

```
v = %R plot(X,Y)
assert v == None
```

In [12]:

```
v = %R print(X)
assert v == None
```

But, if the last value did not print anything to console, the value is returned:

In [13]:

```
v = %R print(summary(X)); X
print 'v:', v
```

The return value can be suppressed by a trailing ';' or an -n argument.

In [14]:

```
%R -n X
```

In [15]:

```
%R X;
```

Often, we will want to do more than a simple linear regression model. There may be several lines of R code that we want to use before returning to python. This is the cell-level magic.

For the cell level magic, inputs can be passed via the -i or --inputs argument in the line. These variables are copied from the shell namespace to R's namespace using rpy2.robjects.r.assign. It would be nice not to have to copy these into R: rnumpy ( http://bitbucket.org/njs/rnumpy/wiki/API ) has done some work to limit or at least make transparent the number of copies of an array. This seems like a natural thing to try to build on. Arrays can be output from R via the -o or --outputs argument in the line. All other arguments are sent to R's png function, which is the graphics device used to create the plots.

We can redo the above calculations in one ipython cell. We might also want to add some output such as a summary from R or perhaps the standard plotting diagnostics of the lm.

In [16]:

```
%%R -i X,Y -o XYcoef
XYlm = lm(Y~X)
XYcoef = coef(XYlm)
print(summary(XYlm))
par(mfrow=c(2,2))
plot(XYlm)
```

Currently, data is passed through RMagics.pyconverter when going from python to R and RMagics.Rconverter when going from R to python. These currently default to numpy.ndarray. Future work will involve writing better converters, most likely involving integration with http://pandas.sourceforge.net.

Passing ndarrays into R seems to require a copy, though once an object is returned to python, this object is NOT copied, and it is possible to change its values.

In [17]:

```
seq1 = np.arange(10)
```

In [18]:

```
%%R -i seq1 -o seq2
seq2 = rep(seq1, 2)
print(seq2)
```

In [19]:

```
seq2[::2] = 0
seq2
```

Out[19]:

In [20]:

```
%%R
print(seq2)
```

In [21]:

```
seq1[0] = 200
%R print(seq1)
```

In [22]:

```
print seq1
%R -i seq1 -o seq1
print seq1
seq1[0] = 200
%R print(seq1)
seq1_view = %R seq1
assert(id(seq1_view.data) == id(seq1.data))
```

Exceptions are handled by passing back rpy2's exception and the line that triggered it.

In [23]:

```
try:
%R -n nosuchvar
except Exception as e:
print e.message
pass
```

In [24]:

```
datapy= np.array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c')],
dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')])
```

In [25]:

```
%%R -i datapy -d datar
datar = datapy
```

In [26]:

```
datar
```

Out[26]:

In [27]:

```
%R datar2 = datapy
%Rpull -d datar2
datar2
```

Out[27]:

In [28]:

```
%Rget -d datar2
```

Out[28]:

In [29]:

```
Z = np.arange(6)
%R -i Z
%Rget -d Z
```

Out[29]:

In [30]:

```
%Rget datar2
```

Out[30]:

In [30]:

```
```