我有一个非常标准的 csv 数据集,我正在尝试使用 rpy2/Rmagic 在 IPython Notebook 中读取它:
# R code
%load_ext rmagic
%R my.data <- read.csv("/Users/xxx/Documents/data.csv")
我收到此错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-31-844400cf68c6> in <module>()
25 ####Chunk 1: Inputting and checking the data
---> 27 get_ipython().magic(u'R my.data <- read.csv("/Users/xxx/Documents/data.csv")')
28 get_ipython().magic(u'R summary(my.data)')
/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
2162 magic_name, _, magic_arg_s = arg_s.partition(' ')
2163 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2164 return self.run_line_magic(magic_name, magic_arg_s)
2165
2166 #-------------------------------------------------------------------------
/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
2088 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2089 with self.builtin_trap:
-> 2090 result = fn(*args,**kwargs)
2091 return result
2092
/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/extensions/rmagic.pyc in R(self, line, cell, local_ns)
/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
189 # but it's overkill for just that one bit of state.
190 def magic_deco(arg):
--> 191 call = lambda f, *a, **k: f(*a, **k)
192
193 if callable(arg):
/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/extensions/rmagic.pyc in R(self, line, cell, local_ns)
579 if return_output and not args.noreturn:
580 if result != ri.NULL:
--> 581 return self.Rconverter(result, dataframe=False)
582
583 __doc__ = __doc__.format(
/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/extensions/rmagic.pyc in Rconverter(Robj, dataframe)
113 return np.asarray(Robj)
114 Robj = np.rec.fromarrays(Robj, names = names)
--> 115 return np.asarray(Robj)
116
117 @magics_class
/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
233
234 """
--> 235 return array(a, dtype, copy=False, order=order)
236
237 def asanyarray(a, dtype=None, order=None):
TypeError: __float__ returned non-float (type rpy2.rinterface.NAIntegerType)
我猜这与我的 csv 数据中的 NA 值有关。我实际上并没有在那里输入一个值——只是一个空白条目(例如 1、3、4)。
我尝试用 NA、空格、0 等替换空白条目——我总是遇到同样的错误。我究竟做错了什么?
编辑:我尝试使用纯 rpy2 进行操作(不对我的数据集进行任何更改):
import rpy2.robjects as robjects
myData = robjects.r['read.csv']("/Users/xxx/Documents/data.csv")
print robjects.r['summary'](myData)
它工作正常!所以这一定是 IPython/Rmagic 的东西。