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

Viewed 162

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)

EDIT

I tried to implement the answer of @lgautier as follows:

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
           ''')

x3 = robjects.r['x2']

but I got the following error message

R[write to console]: Error in (function (expr, envir = parent.frame(), enclos = if (is.list(envir) ||  :
  object 'x1' not found

What am I doing wrong?

2 Answers

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])
>>>

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])
# Python knows about x1, you defined it right above.
print(x1)
# R does not know any x1 unless you have defined it before.
robjects.r('''
           x2 = x1  
           x2[1] = x2[1] + 1 ## some R specific function
           ''')

To define x1 in the R global environment, try:

robjects.globalenv['x1'] = 123

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