1
# -*- coding: utf-8 -*-
7
Magic command interface for interactive work with R via rpy2
30
#-----------------------------------------------------------------------------
31
# Copyright (C) 2012 The IPython Development Team
33
# Distributed under the terms of the BSD License. The full license is in
34
# the file COPYING, distributed as part of this software.
35
#-----------------------------------------------------------------------------
40
from shutil import rmtree
41
from getopt import getopt
43
# numpy and rpy2 imports
47
import rpy2.rinterface as ri
48
import rpy2.robjects as ro
49
from rpy2.robjects.numpy2ri import numpy2ri
50
ro.conversion.py2ri = numpy2ri
54
from IPython.core.displaypub import publish_display_data
55
from IPython.core.magic import (Magics, magics_class, cell_magic, line_magic,
57
from IPython.testing.skipdoctest import skip_doctest
58
from IPython.core.magic_arguments import (
59
argument, magic_arguments, parse_argstring
61
from IPython.utils.py3compat import str_to_unicode, unicode_to_str, PY3
63
class RInterpreterError(ri.RRuntimeError):
64
"""An error when running R code in a %%R magic cell."""
65
def __init__(self, line, err, stdout):
67
self.err = err.rstrip()
68
self.stdout = stdout.rstrip()
70
def __unicode__(self):
71
s = 'Failed to parse and evaluate line %r.\nR error message: %r' % \
73
if self.stdout and (self.stdout != self.err):
74
s += '\nR stdout:\n' + self.stdout
81
return unicode_to_str(unicode(self), 'utf-8')
83
def Rconverter(Robj, dataframe=False):
85
Convert an object in R's namespace to one suitable
86
for ipython's namespace.
88
For a data.frame, it tries to return a structured array.
89
It first checks for colnames, then names.
90
If all are NULL, it returns np.asarray(Robj), else
91
it tries to construct a recarray
96
Robj: an R object returned from rpy2
98
is_data_frame = ro.r('is.data.frame')
99
colnames = ro.r('colnames')
100
rownames = ro.r('rownames') # with pandas, these could be used for the index
101
names = ro.r('names')
104
as_data_frame = ro.r('as.data.frame')
105
cols = colnames(Robj)
108
Robj = as_data_frame(Robj)
109
names = tuple(np.array(cols))
110
elif _names != ri.NULL:
111
names = tuple(np.array(_names))
112
else: # failed to find names
113
return np.asarray(Robj)
114
Robj = np.rec.fromarrays(Robj, names = names)
115
return np.asarray(Robj)
118
class RMagics(Magics):
119
"""A set of magics useful for interactive work with R via rpy2.
122
def __init__(self, shell, Rconverter=Rconverter,
123
pyconverter=np.asarray,
124
cache_display_data=False):
129
shell : IPython shell
131
pyconverter : callable
132
To be called on values in ipython namespace before
133
assigning to variables in rpy2.
135
cache_display_data : bool
136
If True, the published results of the final call to R are
137
cached in the variable 'display_cache'.
140
super(RMagics, self).__init__(shell)
141
self.cache_display_data = cache_display_data
145
self.Rstdout_cache = []
146
self.pyconverter = pyconverter
147
self.Rconverter = Rconverter
149
def eval(self, line):
151
Parse and evaluate a line with rpy2.
152
Returns the output to R's stdout() connection
153
and the value of eval(parse(line)).
155
old_writeconsole = ri.get_writeconsole()
156
ri.set_writeconsole(self.write_console)
158
value = ri.baseenv['eval'](ri.parse(line))
159
except (ri.RRuntimeError, ValueError) as exception:
160
warning_or_other_msg = self.flush() # otherwise next return seems to have copy of error
161
raise RInterpreterError(line, str_to_unicode(str(exception)), warning_or_other_msg)
162
text_output = self.flush()
163
ri.set_writeconsole(old_writeconsole)
164
return text_output, value
166
def write_console(self, output):
168
A hook to capture R's stdout in a cache.
170
self.Rstdout_cache.append(output)
174
Flush R's stdout cache to a string, returning the string.
176
value = ''.join([str_to_unicode(s, 'utf-8') for s in self.Rstdout_cache])
177
self.Rstdout_cache = []
182
def Rpush(self, line):
184
A line-level magic for R that pushes
185
variables from python to rpy2. The line should be made up
186
of whitespace separated variable names in the IPython
189
In [7]: import numpy as np
191
In [8]: X = np.array([4.5,6.3,7.9])
194
Out[9]: 6.2333333333333343
199
Out[11]: array([ 6.23333333])
203
inputs = line.split(' ')
205
self.r.assign(input, self.pyconverter(self.shell.user_ns[input]))
210
'-d', '--as_dataframe', action='store_true',
212
help='Convert objects to data.frames before returning to ipython.'
219
def Rpull(self, line):
221
A line-level magic for R that pulls
222
variables from python to rpy2::
224
In [18]: _ = %R x = c(3,4,6.7); y = c(4,6,7); z = c('a',3,4)
226
In [19]: %Rpull x y z
229
Out[20]: array([ 3. , 4. , 6.7])
232
Out[21]: array([ 4., 6., 7.])
236
array(['a', '3', '4'],
240
If --as_dataframe, then each object is returned as a structured array
241
after first passed through "as.data.frame" in R before
242
being calling self.Rconverter.
243
This is useful when a structured array is desired as output, or
244
when the object in R has mixed data types.
245
See the %%R docstring for more examples.
250
Beware that R names can have '.' so this is not fool proof.
251
To avoid this, don't name your R objects with '.'s...
254
args = parse_argstring(self.Rpull, line)
255
outputs = args.outputs
256
for output in outputs:
257
self.shell.push({output:self.Rconverter(self.r(output),dataframe=args.as_dataframe)})
262
'-d', '--as_dataframe', action='store_true',
264
help='Convert objects to data.frames before returning to ipython.'
272
def Rget(self, line):
274
Return an object from rpy2, possibly as a structured array (if possible).
275
Similar to Rpull except only one argument is accepted and the value is
276
returned rather than pushed to self.shell.user_ns::
278
In [3]: dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')]
280
In [4]: datapy = np.array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5, 'e')], dtype=dtype)
286
array([['1', '2', '3', '4'],
287
['2', '3', '2', '5'],
288
['a', 'b', 'c', 'e']],
291
In [7]: %Rget -d datapy
293
array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5.0, 'e')],
294
dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')])
297
args = parse_argstring(self.Rget, line)
299
return self.Rconverter(self.r(output[0]),dataframe=args.as_dataframe)
305
'-i', '--input', action='append',
306
help='Names of input variable from shell.user_ns to be assigned to R variables of the same names after calling self.pyconverter. Multiple names can be passed separated only by commas with no whitespace.'
309
'-o', '--output', action='append',
310
help='Names of variables to be pushed from rpy2 to shell.user_ns after executing cell body and applying self.Rconverter. Multiple names can be passed separated only by commas with no whitespace.'
313
'-w', '--width', type=int,
314
help='Width of png plotting device sent as an argument to *png* in R.'
317
'-h', '--height', type=int,
318
help='Height of png plotting device sent as an argument to *png* in R.'
322
'-d', '--dataframe', action='append',
323
help='Convert these objects to data.frames and return as structured arrays.'
326
'-u', '--units', type=int,
327
help='Units of png plotting device sent as an argument to *png* in R. One of ["px", "in", "cm", "mm"].'
330
'-p', '--pointsize', type=int,
331
help='Pointsize of png plotting device sent as an argument to *png* in R.'
335
help='Background of png plotting device sent as an argument to *png* in R.'
339
help='Force the magic to not return anything.',
348
def R(self, line, cell=None):
350
Execute code in R, and pull some of the results back into the Python namespace.
352
In line mode, this will evaluate an expression and convert the returned value to a Python object.
353
The return value is determined by rpy2's behaviour of returning the result of evaluating the
356
Multiple R lines can be executed by joining them with semicolons::
358
In [9]: %R X=c(1,4,5,7); sd(X); mean(X)
359
Out[9]: array([ 4.25])
361
As a cell, this will run a block of R code, without bringing anything back by default::
365
....: print(summary(lm(Y~X)))
373
0.88 -0.24 -2.28 1.64
376
Estimate Std. Error t value Pr(>|t|)
377
(Intercept) 0.0800 2.3000 0.035 0.975
378
X 1.0400 0.4822 2.157 0.164
380
Residual standard error: 2.088 on 2 degrees of freedom
381
Multiple R-squared: 0.6993,Adjusted R-squared: 0.549
382
F-statistic: 4.651 on 1 and 2 DF, p-value: 0.1638
384
In the notebook, plots are published as the output of the cell.
388
will create a scatter plot of X bs Y.
390
If cell is not None and line has some R code, it is prepended to
393
Objects can be passed back and forth between rpy2 and python via the -i -o flags in line::
395
In [14]: Z = np.array([1,4,5,10])
397
In [15]: %R -i Z mean(Z)
398
Out[15]: array([ 5.])
401
In [16]: %R -o W W=Z*mean(Z)
402
Out[16]: array([ 5., 20., 25., 50.])
405
Out[17]: array([ 5., 20., 25., 50.])
407
The return value is determined by these rules:
409
* If the cell is not None, the magic returns None.
411
* If the cell evaluates as False, the resulting value is returned
412
unless the final line prints something to the console, in
413
which case None is returned.
415
* If the final line results in a NULL value when evaluated
416
by rpy2, then None is returned.
418
* No attempt is made to convert the final value to a structured array.
419
Use the --dataframe flag or %Rget to push / return a structured array.
421
* If the -n flag is present, there is no return value.
423
* A trailing ';' will also result in no return value as the last
424
value in the line is an empty string.
426
The --dataframe argument will attempt to return structured arrays.
427
This is useful for dataframes with
428
mixed data types. Note also that for a data.frame,
429
if it is returned as an ndarray, it is transposed::
431
In [18]: dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')]
433
In [19]: datapy = np.array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5, 'e')], dtype=dtype)
435
In [20]: %%R -o datar
441
array([['1', '2', '3', '4'],
442
['2', '3', '2', '5'],
443
['a', 'b', 'c', 'e']],
446
In [22]: %%R -d datar
452
array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5.0, 'e')],
453
dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')])
455
The --dataframe argument first tries colnames, then names.
456
If both are NULL, it returns an ndarray (i.e. unstructured)::
458
In [1]: %R mydata=c(4,6,8.3); NULL
463
Out[3]: array([ 4. , 6. , 8.3])
465
In [4]: %R names(mydata) = c('a','b','c'); NULL
471
array((4.0, 6.0, 8.3),
472
dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])
477
Out[8]: array([ 4. , 6. , 8.3])
481
args = parse_argstring(self.R, line)
483
# arguments 'code' in line are prepended to
491
return_output = False
494
code = ' '.join(args.code) + code
497
for input in ','.join(args.input).split(','):
498
self.r.assign(input, self.pyconverter(self.shell.user_ns[input]))
500
png_argdict = dict([(n, getattr(args, n)) for n in ['units', 'height', 'width', 'bg', 'pointsize']])
501
png_args = ','.join(['%s=%s' % (o,v) for o, v in png_argdict.items() if v is not None])
502
# execute the R code in a temporary directory
504
tmpd = tempfile.mkdtemp()
505
self.r('png("%s/Rplots%%03d.png",%s)' % (tmpd, png_args))
509
for line in code.split(';'):
510
text_result, result = self.eval(line)
511
text_output += text_result
513
# the last line printed something to the console so we won't return it
514
return_output = False
516
text_result, result = self.eval(code)
517
text_output += text_result
521
# read out all the saved .png files
523
images = [open(imgfile, 'rb').read() for imgfile in glob("%s/Rplots*png" % tmpd)]
525
# now publish the images
526
# mimicking IPython/zmq/pylab/backend_inline.py
528
mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' }
529
mime = mimetypes[fmt]
531
# publish the printed R objects, if any
535
display_data.append(('RMagic.R', {'text/plain':text_output}))
537
# flush text streams before sending figures, helps a little with output
539
# synchronization in the console (though it's a bandaid, not a real sln)
540
sys.stdout.flush(); sys.stderr.flush()
541
display_data.append(('RMagic.R', {mime: image}))
543
# kill the temporary directory
546
# try to turn every output into a numpy array
547
# this means that output are assumed to be castable
551
for output in ','.join(args.output).split(','):
552
self.shell.push({output:self.Rconverter(self.r(output), dataframe=False)})
555
for output in ','.join(args.dataframe).split(','):
556
self.shell.push({output:self.Rconverter(self.r(output), dataframe=True)})
558
for tag, disp_d in display_data:
559
publish_display_data(tag, disp_d)
561
# this will keep a reference to the display_data
562
# which might be useful to other objects who happen to use
565
if self.cache_display_data:
566
self.display_cache = display_data
568
# if in line mode and return_output, return the result as an ndarray
569
if return_output and not args.noreturn:
570
if result != ri.NULL:
571
return self.Rconverter(result, dataframe=False)
573
__doc__ = __doc__.format(
574
R_DOC = ' '*8 + RMagics.R.__doc__,
575
RPUSH_DOC = ' '*8 + RMagics.Rpush.__doc__,
576
RPULL_DOC = ' '*8 + RMagics.Rpull.__doc__,
577
RGET_DOC = ' '*8 + RMagics.Rget.__doc__
582
def load_ipython_extension(ip):
583
"""Load the extension in IPython."""
586
ip.register_magics(RMagics)