%pylab inline
rmagic
extension that contains a some magic functions for working with R via rpy2.%load_ext
magic as follows:%load_ext rmagic
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)
%Rpush
copies its arguments to variables of the same name in rpy2%R
line magic evaluates the string in rpy2 and returns the result%Rpush X Y
%R lm(Y~X)$coef
We can check that this is correct fairly easily:
Xr = X - X.mean(); Yr = Y - Y.mean()
slope = (Xr*Yr).sum() / (Xr**2).sum()
intercept = Y.mean() - X.mean() * slope
(intercept, slope)
It is also possible to return more than one value with %R.
%R resid(lm(Y~X)); coef(lm(Y~X))
coef(lm(X~Y))
.%Rpull
and %Rget
a
in rpy2's namespace.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
%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.
A = np.arange(20)
%R -i A
%R mean(A)
The magic %Rget retrieves one variable from R.
%Rget A
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
%R
will not return anything in this case.%R
returns None.v = %R plot(X,Y)
assert v == None
Also, if the return value of a call to %R (inline mode) has just been printed to the console, then its value is also not returned.
v = %R print(X)
assert v == None
v = %R print(summary(X)); X
print 'v:', v
%R -n X
%R X;
rpy2.robjects.r.assign
%%R -i X,Y -o XYcoef
XYlm = lm(Y~X)
XYcoef = coef(XYlm)
print(summary(XYlm))
par(mfrow=c(2,2))
plot(XYlm)
RMagics.pyconverter
when going from python to R and RMagics.Rconverter
when going from R to python.seq1 = np.arange(10)
%%R -i seq1 -o seq2
seq2 = rep(seq1, 2)
print(seq2)
seq2[::2] = 0
seq2
%%R
print(seq2)
seq1[0] = 200
%R print(seq1)
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.
try:
%R -n nosuchvar
except Exception as e:
print e
datapy= np.array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c')],
dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')])
%%R -i datapy -d datar
datar = datapy
datar
%R datar2 = datapy
%Rpull -d datar2
datar2
%Rget -d datar2
For arrays without names, the -d argument has no effect because the R object has no colnames or names.
Z = np.arange(6)
%R -i Z
%Rget -d Z
%Rget datar2