rpy2 / dataframe访问中的命名列表等效项

时间:2015-07-02 17:20:45

标签: python r pandas rpy2

我试图以两种不同的方式从rpy2中复制R中的MNP包中的示例。首先,我只是使用robjects.r一个字符串来完全复制和粘贴R代码:

import rpy2.robjects as robjects
import rpy2.robjects.numpy2ri
import rpy2.robjects.pandas2ri
import rpy2.robjects.packages as rpackages

robjects.pandas2ri.activate()
mnp = rpackages.importr('MNP')
base = rpackages.importr('base')

r = robjects.r
r.data('detergent')
rcmd = '''\
mnp(choice ~ 1, choiceX = list(Surf=SurfPrice, Tide=TidePrice,
Wisk=WiskPrice, EraPlus=EraPlusPrice,
Solo=SoloPrice, All=AllPrice),
cXnames = "price", data = detergent, n.draws = 500, burnin = 100,
thin = 3, verbose = TRUE)'''

res = r(rcmd)

这很好用,可以直接在R中重现我的工作。我还想尝试使用python可访问对象运行这段代码,从数据帧传入数据:

import rpy2.rlike.container as rlc
df = robjects.pandas2ri.ri2py(r['detergent'])

choiceX = rlc.TaggedList(['SurfPrice', 'TidePrice', 'WiskPrice', 'EraPlusPrice', 'SoloPrice', 'AllPrice'], 
                         tags=('Surf', 'Tide', 'Wisk', 'EraPlus', 'Solo', 'All'))

res = mnp.mnp('choice ~ 1', 
              choiceX=['SurfPrice', 'TidePrice', 'WiskPrice', 'EraPlusPrice', 'SoloPrice', 'AllPrice'],
              cXnames='price', 
              data=df, n_draws=500, burnin=100,
              thin=3, verbose=True)

失败并显示错误:

Error in xmatrix.mnp(formula, data = eval.parent(data), choiceX = call$choiceX,  : 
  Error: Invalid input for `choiceX.'
 You must specify the choice-specific varaibles at least for all non-base categories.

在另一个SO response中建议使用rpy2 TaggedList替换R命名列表。如果我删除了MNP的choiceXcXnames参数(它们是可选的),代码就会运行,所以看起来pandas数据帧正在正确传递。

我不确定TaggedList在进入R后是否被正确解释为命名列表,或者如果MNP没有将choiceX的内容与熊猫数据框。

任何人都有关于这里会发生什么的想法?

更新

按照@ lgautier的建议,我将代码修改为:

choiceX = rlc.TaggedList([base.as_symbol('SurfPrice'), base.as_symbol('TidePrice'), 
                          base.as_symbol('WiskPrice'), base.as_symbol('EraPlusPrice'), 
                          base.as_symbol('SoloPrice'), base.as_symbol('AllPrice')], 
                         tags=('Surf', 'Tide', 'Wisk', 'EraPlus', 'Solo', 'All'))

res = mnp.mnp(robjects.Formula('choice ~ 1'), 
              choiceX=choiceX,
              cXnames='price', 
              data=df, n_draws=500, burnin=100,
              thin=3, verbose=True)

但是,我收到的错误与之前发布的相同。

更新2

按照@lgautier建议的解决方法,使用以下代码:

choiceX = rlc.TaggedList([base.as_symbol('SurfPrice'),
                          base.as_symbol('TidePrice'), 
                          base.as_symbol('WiskPrice'),
                          base.as_symbol('EraPlusPrice'), 
                          base.as_symbol('SoloPrice'),
                          base.as_symbol('AllPrice')], 
                         tags=('Surf', 'Tide', 'Wisk',
                               'EraPlus', 'Solo', 'All'))

choiceX = robjects.conversion.py2ro(choiceX)
# add the names
choiceX.names = robjects.vectors.StrVector(('Surf', 'Tide',
                                            'Wisk', 'EraPlus',
                                            'Solo', 'All'))

res = mnp.mnp(robjects.Formula('choice ~ 1'), 
              choiceX=choiceX,
              cXnames='price', 
              data=df, n_draws=500, burnin=100,
              thin=3, verbose=True)

仍然会产生错误(虽然不同):

Error in as.vector(x, mode) : 
  cannot coerce type 'symbol' to vector of type 'any'
---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-21-7de5ad805801> in <module>()
      3               cXnames='price',
      4               data=df, n_draws=500, burnin=100,
----> 5               thin=3, verbose=True)

/Users/lev/anaconda/envs/rmnptest/lib/python2.7/site-packages/rpy2-2.5.6-py2.7-macosx-10.5-x86_64.egg/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
    168                 v = kwargs.pop(k)
    169                 kwargs[r_k] = v
--> 170         return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
    171 
    172 pattern_link = re.compile(r'\\link\{(.+?)\}')

/Users/lev/anaconda/envs/rmnptest/lib/python2.7/site-packages/rpy2-2.5.6-py2.7-macosx-10.5-x86_64.egg/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
     98         for k, v in kwargs.items():
     99             new_kwargs[k] = conversion.py2ri(v)
--> 100         res = super(Function, self).__call__(*new_args, **new_kwargs)
    101         res = conversion.ri2ro(res)
    102         return res

RRuntimeError: Error in as.vector(x, mode) : 
  cannot coerce type 'symbol' to vector of type 'any'

1 个答案:

答案 0 :(得分:1)

Python代码与您的R不对应。您发布后就发现了这一点,因此请在下面详细说明。总结是R符号和Python字符串不相等(尽管R在某些地方允许两者同时使其自己的用户感到困惑 - 例如,library("MNP")library(MNP)都可以工作。

这与此问题没有什么不同:pandas and rpy2: Why does ezANOVA work via robjects.r but not robjects.packages.importr?

...除了choiceX将是未评估的R表达式而不仅仅是符号。

R代码是:

data(detergent)
mnp(choice ~ 1,
    # ^- this is a "formula", which is an expression in R
    choiceX = list(Surf=SurfPrice, Tide=TidePrice,
                   Wisk=WiskPrice, EraPlus=EraPlusPrice,
                   Solo=SoloPrice, All=AllPrice),
    # ^- this is a list of objects, but with the cautionary note
    #    that R evaluates expressions in argument lazily. Therefore
    #    the safest is to have it as an R expression (it may or may
    #    not work if evaluated, but this depends on the code in
    #    `mnp`)
    cXnames = "price",
    # ^- this is a string
    data = detergent,
    n.draws = 500, burnin = 100,
    thin = 3, verbose = TRUE)

你拥有的Python(有关差异的评论):

choiceX = rlc.TaggedList(['SurfPrice', 'TidePrice', 'WiskPrice',
                          'EraPlusPrice', 'SoloPrice', 'AllPrice'], 
                         tags=('Surf', 'Tide', 'Wisk',
                               'EraPlus', 'Solo', 'All'))
# ^- this is a "tagged list", and the R equivalent would be
#    list(Surf="SurfPrice", Tide="TidePrice", Wisk="WiskPrice",
#         EraPlus="EraPlusPrice", Solo="SoloPrice", All="AllPrice")
#    Something closer to your R code above would be:
#    rlc.TaggedList([as_symbol('SurfPrice'), as_symbol('TidePrice'),
#                   ...
#                   tags=('Surf', 'Tide', ...))

res = mnp.mnp('choice ~ 1', 
              # ^- this is a string. To make it an R formula, do
              # robjects.Formula('choice ~ 1')
              choiceX=['SurfPrice', 'TidePrice', 'WiskPrice',
                       'EraPlusPrice', 'SoloPrice', 'AllPrice'],
              # ^- this should be choiceX defined above, I guess
              cXnames='price',
              # ^- this is a string, like in R 
              data=df,
              n_draws=500, burnin=100,
              thin=3, verbose=True)

修改

现在这意味着以下内容应该有效

choiceX = robjects.rinterface.parse("""
    list(Surf=SurfPrice, Tide=TidePrice,
         Wisk=WiskPrice, EraPlus=EraPlusPrice,
         Solo=SoloPrice, All=AllPrice)""")

目前rpy2没有为构建R表达式提供许多实用程序。如果变量名是Python级别的参数 你可以考虑这样的事情:

rcode = 'list('+''.join('%s=%s' % (k,v) \
                        for k,v in \
                        (('Surf','SurfPrice'),
                         ('Tide', 'TidePrice'),
                         ('Wisk','WiskPrice'),
                         ('EraPlus','EraPlusPrice'),
                         ('Solo','SoloPrice'),
                         ('All','AllPrice'))) + ')'
choiceX = robjects.rinterface.parse(rcode)