converting a Python list to an R numeric vector

2019-06-14 02:29发布

I need to fit my data into a Beta distribution and retrieve the alpha parameter.

I've been coding in Python, but there doesn't seem to be any beta fitting function in SciPy. Either I do everything in Matlab, which I'm not too familiar with, or in Python with R and its fitdistr function. So I went for the latter.

from rpy2.robjects.packages import importr

MASS = importr('MASS')

Then I take my numpy vector of floats in the range [0,1) and I pass it to fitdistr:

myVector = myVector.tolist()
MASS.fitdistr(myVector,"beta")

Too bad that it wants some kind of other vector. Weren't rpy and rpy2 supposed to do all the conversions for me?

Error in function (x, densfun, start, ...)  : 
  'x' must be a non-empty numeric vector
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 82, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 34, in __call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in function (x, densfun, start, ...)  : 
  'x' must be a non-empty numeric vector

What do I need to do here?

1条回答
放荡不羁爱自由
2楼-- · 2019-06-14 03:19

The answer was here: Converting python objects for rpy2

import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()

See http://rpy.sourceforge.net/rpy2/doc/html/numpy.html:

查看更多
登录 后发表回答