Commit 1b83a040 authored by Dirk Eddelbuettel's avatar Dirk Eddelbuettel

Import Upstream version 2.8.6

Laurent Gautier
Copyright Laurent Gautier 2008-2010
People have contributed suggestions or patches; they are thanked here,
rpy2 is much better because of them.
rpy2 is making a limited use (if much left) of code from:
RPy -
(in rinteface/rinterface.c)
Copyright Walter Moreira 2002-2003
Copyright Gregory Warnes 2003-2008
Parseltongue project -
(in rinterface/rinterface.c)
Copyright Alexander Belopolsky - 2006
global-include README
global-exclude *patch* *diff* .hg
include MANIFEST
include gpl-2.0.txt
include rpy/rinterface/_rinterface.h
include rpy/rinterface/_rinterface.c
include rpy/rinterface/sexp.c
include rpy/rinterface/sexp.h
include rpy/rinterface/array.c
include rpy/rinterface/array.h
include rpy/rinterface/buffer.c
include rpy/rinterface/buffer.h
include rpy/rinterface/sequence.c
include rpy/rinterface/sequence.h
include rpy/rinterface/na_values.c
include rpy/rinterface/na_values.h
include rpy/rinterface/null_value.c
include rpy/rinterface/null_value.h
include rpy/rinterface/embeddedr.c
include rpy/rinterface/embeddedr.h
include rpy/rinterface/r_utils.c
include rpy/rinterface/r_utils.h
include rpy/rinterface/_rpy_device.c
include rpy/rinterface/rpy_device.h
include rpy/rinterface/rexternalptr.c
include rpy/rinterface/rexternalptr.h
include rpy/rinterface/*.py
include rpy/rinterface/tests/*.py
include rpy/
include rpy/
include rpy/
include rpy/
recursive-include rpy/robjects *.py
recursive-include rpy/ipython *.py
recursive-include rpy/interactive *.py
recursive-include rpy/rlike *.py
prune dist
include doc/Makefile
include doc/source/rpy2_logo.png
This diff is collapsed.
Metadata-Version: 1.1
Name: rpy2
Version: 2.8.6
Summary: Python interface to the R language (embedded R)
Author: Laurent Gautier
License: GPLv2+
Description: UNKNOWN
Platform: UNKNOWN
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.5
Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Development Status :: 5 - Production/Stable
Requires: six
This is the source tree or distribution for the rpy2 package.
.. image::
`pip` should work out of the box:
pip install rpy2
The package is known to compile on Linux, MacOSX, and Windows
(provided that developper tools are installed, and you are ready
figure out how by yourself).
Alternatively, there is a Docker image available to try rpy2 out
without concerns about the installation process.
To run the ipython console:
docker run -it --rm -p 8888:8888 \
rpy2/rpy2:2.8.x ipython
To run jupypter notebook on port 8888:
docker run --rm -p 8888:8888 \
More information about Docker images can be found in the
`documentation <doc/overview.rst>`_.
In case you find yourself with this source without any idea
of what it takes to compile anything on your platform, try first
python install
If this fails, consider looking for pre-compiled binaries (they are available on Linux Red Hat,
CentOS, Debian, Ubuntu, etc...) or using the matching Docker container.
Note that `python develop` will appear to work, but will result in an
installation from the `rpy` directory here. The namespaces will be
incorrect, so don't do that!
Documentation is available either in the source tree (to be built),
or online (see the rpy home page on sourceforge).
The testing machinery uses the new unittest functionality, requiring python 2.7+
(or potentially the backported unittest2 library for older python, but this is
not supported). The test suite can be run (once rpy2 is installed) as follows:
python -m rpy2.tests
By providing an argument, like "-v", you'll get verbose output.
Individual tests can be run as follows:
python -m unittest rpy2.robjects.tests.testVector
Test discovery can be attempted as follows (not that it may not work):
python -m unittest discover rpy2.robjects
Prefer `python -m rpy2.tests` to run all tests.
RPy2 can be used under the terms of the GNU
General Public License Version 2 or later (see the file
gpl-2.0.txt). This is the very same license R itself is released under.
# Makefile for Sphinx documentation
# You can set these variables from the command line.
SPHINXBUILD = sphinx-build
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
# the i18n builder cannot share the environment and doctrees with the others
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " rpy2demo_graphics to build the figures used in the documentation about graphics"
@echo " rpy2demo_benchmark to build the figure(s) used in the documentation about benchmarks"
@echo " notebooks to build the ipython notebooks used in the documentation"
rm -rf $(BUILDDIR)/*
@cd _static/demos && python
@cd _static/demos && python
rpy2demo_all: rpy2demo_graphics rpy2demo_benchmark
# rule to build ipython notebooks from markdown
notebooks/%.ipynb : notebooks/
notedown \
--precode 'from functools import partial' \
'from rpy2.ipython import html' \
'html.html_rdataframe=partial(html.html_rdataframe, table_class="docutils")' \
--run \
-o $@ \
cp $@ _static/notebooks/
# rule to build sphinx-friendly ReST from ipython notebooks
notebooks/%.rst : notebooks/%.ipynb
@cd generated_rst && ipython nbconvert --to rst ../$<
# rule to build HTML render of an ipython notebook
_static/notebooks/%.html : notebooks/%.ipynb
ipython nbconvert --to html $< --output $@
MD_NOTEBOOKS := $(basename $(notdir $(wildcard notebooks/*.md)))
_notebooks: $(MD_NOTEBOOKS:%=notebooks/%.rst)
_notebooks_html: $(MD_NOTEBOOKS:%=_static/notebooks/%.html)
@echo "Building IPython notebooks from markdown..."
mkdir -p _static/notebooks
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
@echo "Build finished; now you can process the pickle files."
@echo "Build finished; now you can process the JSON files."
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/rpy2.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/rpy2.qhc"
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/rpy2"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/rpy2"
@echo "# devhelp"
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
@echo "Build finished. The text files are in $(BUILDDIR)/text."
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
@echo "The overview file is in $(BUILDDIR)/changes."
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
This directory contains rst files dynamically generated.
\ No newline at end of file
This diff is collapsed.
__version_vector__ = ((2,8,6), '')
__version__ = '.'.join([str(x) for x in __version_vector__[0]]) + \
'' + __version_vector__[1]
Package to interface with R, with a focus on interactive usage
(REPL approach to code-writing), although the package will work
in non-interactive settings.
The package aims at being simple rather than exhaustively complete
(rpy2.robjects, or rpy2.rinterface, can be used if needed), providing
a comfortable experience with autocompletion-capable python consoles.
from collections import OrderedDict
from rpy2.robjects.packages import _loaded_namespaces
from rpy2.robjects.vectors import IntVector, FloatVector, ComplexVector
from rpy2.robjects.vectors import Array, Matrix
from rpy2.robjects.vectors import StrVector
from rpy2.robjects.vectors import ListVector, DataFrame
from rpy2.robjects.environments import Environment
from rpy2.rinterface import NULL
from rpy2.robjects import Formula, RS4
from rpy2.robjects import methods
from rpy2.robjects import conversion
from rpy2.robjects import help as rhelp
from rpy2.robjects.language import eval
from . import process_revents as revents
from os import linesep
import re
class S4Classes(object):
""" *Very* experimental attempt at getting the S4 classes dynamically
mirrored. """
__instance = None
def __new__(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __setattr__(self, name, value):
raise AttributeError("Attributes cannot be set. Use 'importr'")
#classes = S4Classes()
from rpy2.robjects.packages import importr as _importr
from rpy2.robjects.packages import data
import as rhelp
from rpy2.rinterface import baseenv
from os import linesep
from collections import OrderedDict
import re
class Packages(object):
__instance = None
def __new__(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __setattr__(self, name, value):
raise AttributeError("Attributes cannot be set. Use 'importr'")
packages = Packages()
_loaded_namespaces = baseenv['loadedNamespaces']
def importr(packname, newname = None, verbose = False):
""" Wrapper around rpy2.robjects.packages.importr,
adding the following feature(s):
- package instance added to the pseudo-module 'packages'
assert isinstance(packname, str)
packinstance = _importr(packname, on_conflict = 'warn')
# fix the package name (dots possible in R package names)
if newname is None:
newname = packname.replace('.', '_')
Packages().__dict__[newname] = packinstance
## Currently too slow for a serious usage: R's introspection
## of S4 classes is not fast enough
# d = {}
# for cn in methods.get_classnames(packname):
# class AutoS4(RS4):
# __metaclass__ = methods.RS4Auto_Type
# __rpackagename__ = packname
# __rname__ = cn
# newcn = cn.replace('.', '_')
# d[newcn] = AutoS4
# S4Classes().__dict__[newname] = d
return packinstance
for packname in _loaded_namespaces():
"""This module runs continuous updates for R, such as redrawing graphs when
the plot window is resized. Use the start() and stop() functions to turn
updates on and off.
from rpy2.rinterface import process_revents
import time
import threading
class _EventProcessorThread(threading.Thread):
""" Call rinterface.process_revents(), pausing
for at least EventProcessor.interval between calls. """
_continue = True
def run(self):
while self._continue:
class EventProcessor(object):
""" Processor for R events (Singleton class) """
interval = 0.2
daemon_thread = True
name_thread = 'rpy2_process_revents'
_thread = None
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
def start(self):
""" start the event processor """
if (self._thread is not None) and (self._thread.is_alive()):
raise RuntimeError("Processing of R events already started.")
self._thread = _EventProcessorThread(name = self.name_thread)
def stop(self):
""" stop the event processor """
self._thread._continue = False
thread = property(lambda self: self._thread,
None, None, "Thread that processes the events.")
def start():
""" Start the threaded processing of R events. """
def stop():
""" Stop the threaded processing of R events. """
import unittest
from os.path import dirname
def main():
tr = unittest.TextTestRunner(verbosity = 2)
suite =,
if __name__ == '__main__':
from .rmagic import load_ipython_extension
""" Goodies for ipython """
import os
import tempfile
import io
from rpy2 import robjects
from rpy2.robjects.packages import importr
from rpy2.robjects.lib import ggplot2, grdevices
from IPython.core.display import Image
# automatic plotting of ggplot2 figures in the notebook
class GGPlot(ggplot2.GGPlot):
def png(self, width = 700, height = 500):
""" Build an Ipython "Image" (requires iPython). """
return image_png(self, width=width, height=height)
class GGPlotSVG(ggplot2.GGPlot):
""" The embedding of several SVG figures into one ipython notebook is
giving garbled figures. The SVG functionality is taken out to a
child class.
def svg(self, width = 6, height = 4):
""" Build an Ipython "Image" (requires iPython). """
with grdevices.render_to_bytesio(grdevices.svg,
height=height) as b:
data = b.getvalue()
ip_img = Image(data=data, format='svg', embed=False)
return ip_img
def image_png(gg, width=800, height=400):
with grdevices.render_to_bytesio(grdevices.png,
antialias="subpixel") as b:
data = b.getvalue()
ip_img = Image(data=data, format='png', embed=True)
return ip_img
def display_png(gg, width=800, height=400):
ip_img = image_png(gg, width=width, height=height)
return ip_img._repr_png_()
def set_png_formatter():
# register display func with PNG formatter:
png_formatter = get_ipython().display_formatter.formatters['image/png']
dpi = png_formatter.for_type(ggplot2.GGPlot, display_png)
return dpi
class PNGplot(object):
Context manager
def __init__(self, width=600, height=400):
self._width = width
self._height = height
png_formatter = get_ipython().display_formatter.formatters['image/png']
self._png_formatter = png_formatter
self._for_ggplot = self._png_formatter.for_type(ggplot2.GGPlot)
def __enter__(self):
self._png_formatter.for_type(ggplot2.GGPlot, display_png)
return None
def __exit__(self, exc_type, exc_val, exc_tb):
self._png_formatter.for_type(ggplot2.GGPlot, self._for_ggplot)
return False
This diff is collapsed.
This diff is collapsed.
import unittest
from os.path import dirname
def main():
tr = unittest.TextTestRunner(verbosity = 2)
suite =,
if __name__ == '__main__':
This diff is collapsed.
import os
import sys
import warnings
import subprocess
if ((sys.version_info[0] == 2 and sys.version_info[1] < 7) or
(sys.version_info[0] == 3 and sys.version_info[1] < 3)):
raise RuntimeError(
"Python (>=2.7 and < 3.0) or >=3.3 are required to run rpy2")
class RRuntimeWarning(RuntimeWarning):
def _r_home_from_subprocess():
"""Return the R home directory from calling 'R RHOME'."""
tmp = subprocess.check_output(("R", "RHOME"), universal_newlines=True)
except Exception as exc: # FileNotFoundError, WindowsError, etc
r_home = tmp.split(os.linesep)
if r_home[0].startswith("WARNING"):
r_home = r_home[1]
r_home = r_home[0].strip()
return r_home