假設我x1在 python 環境中有一個向量作為 numpy 陣列。我想將該向量傳輸到 R 環境,使用 R 特定函式進行一些計算,然后獲得另一個向量x2,然后想x2作為 numpy 陣列傳輸回 python。目標是獲得以下輸出:
[1 2 3]
[2 2 3]
這是一個使用 rpy2(或任何其他包)的代碼(在第 9 行之前有效,但在第 9 行之后無效)?
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)
uj5u.com熱心網友回復:
這是一個選項 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')
- 在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])
>>>
uj5u.com熱心網友回復:
在代碼的以下部分中,您宣告了一個Python變數x1,并為其分配了一個 numpy 陣列。R 不會知道它,直到您創建一個 R to 變數(可選地具有相同的名稱)。
x1 = np.array([1,2,3])
print(x1)
robjects.r('''
x2 = x1
x2[1] = x2[1] 1 ## some R specific function
''')
檔案中的介紹在這里涵蓋:https : //rpy2.github.io/doc/latest/html/introduction.html#the-r-instance
除此之外,從numpy陣列到陣列的轉換需要使用轉換器。rpy2可以在有或沒有的情況下運行numpy。檔案在這里:https : //rpy2.github.io/doc/latest/html/numpy.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318522.html
