Search code examples
python-3.xrpy2

Python: RRuntimeError: Error in (function (data = NA, dim = length(data), dimnames = NULL) : 'dims' cannot be of length 0


I am trying to call R functions from python but for some reason which I do not know yet, I am getting an RRuntimeError when I am converting a numeral to R rather than a matrix (Dataframe) to R

For example, consider the following simple example

import rpy2.robjects as robjects, pandas as pd, numpy as np
from rpy2.robjects import r
from rpy2.robjects.numpy2ri import numpy2ri
from rpy2.robjects.packages import importr

df= pd.DataFrame(np.random.random((108, 2)), columns=['Number1','Number2'])
p = 3 

resi1=np.array(df, dtype=float)
p1=np.array(p, dtype=float)

r_resi = numpy2ri(resi1)
r_p1= numpy2ri(p1)

Then the Output is

---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-1-7970a0b7c100> in <module>()
     11 
     12 r_resi = numpy2ri(resi1)
---> 13 r_p1= numpy2ri(p1)

D:\Anaconda3\lib\site-packages\rpy2\robjects\numpy2ri.py in numpy2ri(o)
     80         #FIXME: no dimnames ?
     81         #FIXME: optimize what is below needed/possible ? (other ways to create R arrays ?)
---> 82         res = rinterface.baseenv['array'](vec, dim=dim)
     83     # R does not support unsigned types:
     84     elif o.dtype.kind ==

 "u":

RRuntimeError: Error in (function (data = NA, dim = length(data), dimnames = NULL)  : 
  'dims' cannot be of length 0

I am not sure what is going wrong here?


Solution

  • The converter numpy array -> R array needs needs the dimension of the array. There is none here:

    >>> p1
    array(3.0)
    >>> p1.shape
    ()