Issue
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?
Solution
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])
>>>
Answered By - akrun Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.