Home > Software design >  How to transfer a vector from Python to R (and back) after having done some R specific computations
How to transfer a vector from Python to R (and back) after having done some R specific computations

Time:10-16

Let's say I have a vector x1 as a numpy array in the python environment. I want to transfert that vector to the R environment, do some computations using R specific functions and then get another vector x2 and then want to transfer x2 back to python as a numpy array. The goal is to have the following output:

[1 2 3]
[2 2 3]

Here is a code (which works until the line 9 but not after) using rpy2 (or any other package)?

from rpy2.robjects import FloatVector
from rpy2.robjects.packages import importr
stats = importr('stats')
base = importr('base')
#lmtest = importr("lmtest")
import rpy2.robjects as robjects
import numpy as np

x1 = np.array([1,2,3])
print(x1)
robjects.r('''
        x2 = x1  
        x2[1] = x2[1]   1 ## some R specific function
        ''')
print(x2)

CodePudding user response:

Here is an option with pyper

from pyper import *
import numpy as np

x1 = np.array([1,2,3])
r = R(use_pandas=True)
r.assign('x1', x1)
expr1 = '''x2 = x1;
         x2[1] = x2[1]   1;
         x2'''
r(expr1)
r.get('x2')

-testing on python

>>> from pyper import *
>>> import numpy as np
>>> x1 = np.array([1,2,3])
>>> r = R(use_pandas=True)
>>> r.assign('x1', x1)
>>> expr1 = '''x2 = x1;
         x2[1] = x2[1]   1;
         x2'''
>>> r(expr1)
'try({x2 = x1;\n           x2[1] = x2[1]   1;\n           x2})\n[1] 2 2 3\n'
>>> r.get('x2')
array([2, 2, 3])
>>>

CodePudding user response:

In the following part of your code you declare a Python variable x1 to which you assign a numpy array. R will not know about it until you create an R to variable (optionally with the same name).

x1 = np.array([1,2,3])
print(x1)
robjects.r('''
           x2 = x1  
           x2[1] = x2[1]   1 ## some R specific function
           ''')

The introduction in the documentation covers this here: https://rpy2.github.io/doc/latest/html/introduction.html#the-r-instance

Besides that, converting from and to numpy array requires the use of a converter. rpy2 can function with or without numpy. The documentation is here: https://rpy2.github.io/doc/latest/html/numpy.html

  • Related