在 IPython 笔记本中获取 r data.frame

Getting r data.frame in IPython notebook

从命令行使用 IPython 时,我可以获得 data.frame 对象:

 In [1]: import pandas as pd

 In [2]: df = pd.DataFrame({'a':[1,2,3],'b':[2,4,6]})

 In [3]: df
Out[3]:
   a  b
0  1  2
1  2  4
2  3  6

In [4]: %load_ext rmagic

In [5]: col =df.columns

In [6]: %R -i df,col colnames(df) <- unlist(col); print(is.matrix(df))
[1] FALSE


In [7]: %R rdf <- data.frame(df); print(is.data.frame(rdf))
[1] TRUE


In [8]: %R print(summary(rdf))
       a             b
 Min.   :1.0   Min.   :2
 1st Qu.:1.5   1st Qu.:3
 Median :2.0   Median :4
 Mean   :2.0   Mean   :4
 3rd Qu.:2.5   3rd Qu.:5
 Max.   :3.0   Max.   :6


In [9]: %R -d rdf

In [10]: pydf2 = pd.DataFrame(rdf)

但是,当尝试在笔记本中执行此操作时,它不起作用

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-04a06535eeef> in <module>()
----> 1 get_ipython().magic(u'R -d rdf')

/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
   2203         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2204         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2205         return self.run_line_magic(magic_name, magic_arg_s)
   2206 
   2207     #-------------------------------------------------------------------------

/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
   2124                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2125             with self.builtin_trap:
-> 2126                 result = fn(*args,**kwargs)
   2127             return result
   2128 

/usr/local/lib/python2.7/dist-packages/IPython/extensions/rmagic.pyc in R(self, line, cell, local_ns)

/usr/local/lib/python2.7/dist-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
    191     # but it's overkill for just that one bit of state.
    192     def magic_deco(arg):
--> 193         call = lambda f, *a, **k: f(*a, **k)
    194 
    195         if callable(arg):

/usr/local/lib/python2.7/dist-packages/IPython/extensions/rmagic.pyc in R(self, line, cell, local_ns)
    663         if args.dataframe:
    664             for output in ','.join(args.dataframe).split(','):
--> 665                 self.shell.push({output:self.Rconverter(self.r(output), dataframe=True)})
    666 
    667         for tag, disp_d in display_data:

/usr/local/lib/python2.7/dist-packages/IPython/extensions/rmagic.pyc in Rconverter(Robj, dataframe)
    121         as_data_frame = ro.r('as.data.frame')
    122         cols = colnames(Robj)
--> 123         _names = names(Robj)
    124         if cols != ri.NULL:
    125             Robj = as_data_frame(Robj)

TypeError: 'StrVector' object is not callable

有谁知道如何解决这个问题?

谢谢!

软件和系统摘要:

在 IPython Notebook 中,需要使用 %load_ext rpy2.ipython 而不是 %load_ext rmagic 才能从 R.

获得 data.frame