PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

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

 August 21, 2022     environment-variables, python, r, rpy2, vector     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,205,067

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing