##// 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 import rpy2.rinterface as ri
47 import rpy2.rinterface as ri
48 import rpy2.robjects as ro
48 import rpy2.robjects as ro
49 from rpy2.robjects.numpy2ri import numpy2ri
49 try:
50 ro.conversion.py2ri = numpy2ri
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 # IPython imports
57 # IPython imports
53
58
@@ -58,6 +63,7 b' from IPython.testing.skipdoctest import skip_doctest'
58 from IPython.core.magic_arguments import (
63 from IPython.core.magic_arguments import (
59 argument, magic_arguments, parse_argstring
64 argument, magic_arguments, parse_argstring
60 )
65 )
66 from IPython.external.simplegeneric import generic
61 from IPython.utils.py3compat import str_to_unicode, unicode_to_str, PY3
67 from IPython.utils.py3compat import str_to_unicode, unicode_to_str, PY3
62
68
63 class RInterpreterError(ri.RRuntimeError):
69 class RInterpreterError(ri.RRuntimeError):
@@ -114,16 +120,32 b' def Rconverter(Robj, dataframe=False):'
114 Robj = np.rec.fromarrays(Robj, names = names)
120 Robj = np.rec.fromarrays(Robj, names = names)
115 return np.asarray(Robj)
121 return np.asarray(Robj)
116
122
123 @generic
117 def pyconverter(pyobj):
124 def pyconverter(pyobj):
118 """Convert Python objects to R objects."""
125 """Convert Python objects to R objects. Add types using the decorator:
119 if 'pandas' in sys.modules:
126
120 # We only do this if pandas is already loaded
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):
136 return np.asarray(pyobj)
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:
121 from pandas import DataFrame
142 from pandas import DataFrame
122 if isinstance(pyobj, DataFrame):
123 from pandas.rpy.common import convert_to_r_dataframe
143 from pandas.rpy.common import convert_to_r_dataframe
144 @pyconverter.when_type(DataFrame)
145 def pyconverter_dataframe(pyobj):
124 return convert_to_r_dataframe(pyobj, strings_as_factors=True)
146 return convert_to_r_dataframe(pyobj, strings_as_factors=True)
125
147 except ImportError:
126 return np.asarray(pyobj)
148 pass
127
149
128 @magics_class
150 @magics_class
129 class RMagics(Magics):
151 class RMagics(Magics):
General Comments 0
You need to be logged in to leave comments. Login now