##// END OF EJS Templates
Refactor to prefer rpy2's pandas2ri conversion system.
Thomas Kluyver -
Show More
@@ -46,8 +46,13 b' import numpy as np'
46 46
47 47 import rpy2.rinterface as ri
48 48 import rpy2.robjects as ro
49 from rpy2.robjects.numpy2ri import numpy2ri
50 ro.conversion.py2ri = numpy2ri
49 try:
50 from rpy2.robjects import pandas2ri
51 pandas2ri.activate()
52 except ImportError:
53 pandas2ri = None
54 from rpy2.robjects import numpy2ri
55 numpy2ri.activate()
51 56
52 57 # IPython imports
53 58
@@ -58,6 +63,7 b' from IPython.testing.skipdoctest import skip_doctest'
58 63 from IPython.core.magic_arguments import (
59 64 argument, magic_arguments, parse_argstring
60 65 )
66 from IPython.external.simplegeneric import generic
61 67 from IPython.utils.py3compat import str_to_unicode, unicode_to_str, PY3
62 68
63 69 class RInterpreterError(ri.RRuntimeError):
@@ -114,17 +120,33 b' def Rconverter(Robj, dataframe=False):'
114 120 Robj = np.rec.fromarrays(Robj, names = names)
115 121 return np.asarray(Robj)
116 122
123 @generic
117 124 def pyconverter(pyobj):
118 """Convert Python objects to R objects."""
119 if 'pandas' in sys.modules:
120 # We only do this if pandas is already loaded
121 from pandas import DataFrame
122 if isinstance(pyobj, DataFrame):
123 from pandas.rpy.common import convert_to_r_dataframe
124 return convert_to_r_dataframe(pyobj, strings_as_factors=True)
125 """Convert Python objects to R objects. Add types using the decorator:
125 126
127 @pyconverter.when_type
128 """
129 return pyobj
130
131 # The default conversion for lists seems to make them a nested list. That has
132 # some advantages, but is rarely convenient, so for interactive use, we convert
133 # lists to a numpy array, which becomes an R vector.
134 @pyconverter.when_type(list)
135 def pyconverter_list(pyobj):
126 136 return np.asarray(pyobj)
127 137
138 if pandas2ri is None:
139 # pandas2ri was new in rpy2 2.3.3, so for now we'll fallback to pandas'
140 # conversion function.
141 try:
142 from pandas import DataFrame
143 from pandas.rpy.common import convert_to_r_dataframe
144 @pyconverter.when_type(DataFrame)
145 def pyconverter_dataframe(pyobj):
146 return convert_to_r_dataframe(pyobj, strings_as_factors=True)
147 except ImportError:
148 pass
149
128 150 @magics_class
129 151 class RMagics(Magics):
130 152 """A set of magics useful for interactive work with R via rpy2.
General Comments 0
You need to be logged in to leave comments. Login now