简体   繁体   English

如何使用rpy2从python获取n维数组

[英]how to use rpy2 to get n-dim array from python

I want to use python to some calculations and put the array data to r to get some plot. 我想使用python进行一些计算,然后将数组数据放入r以得到一些图。

For 1-dim array, I can use FloatVector to get right answer, but n-dim array error 对于1维数组,我可以使用FloatVector来获得正确答案,但n维数组错误

(run following code) (运行以下代码)

(2-dim array) (2维数组)
import numpy as np from rpy2.robjects.vectors import FloatVector x = np.array([[1, 2], [3, 4]]) X = FloatVector(x)

error information: 错误信息:

`Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "D:\Program\Anaconda3\lib\site-packages\rpy2\robjects\vectors.py",   line 456, in __init__
 obj = FloatSexpVector(obj)
 ValueError: Error while trying to convert element 0 to a double.`

Using numpy2ri could make error in some plot orders(like ggplot2) 使用numpy2ri可能会使某些绘图顺序出错(例如ggplot2)

I'd like to doing these all in spyder. 我想在间谍中做所有这些。

The conversion mechanism can be your friend: 转换机制可以是您的朋友:

from rpy2.robjects.conversion import localconverter
from rpy2.robjects import numpy2ri

with localconverter(numpy2ri.converter) as cv:
    X = cv.py2ro(x) # convert from *py*thon to *ro*bjects

Otherwise, this is happening because rpy2 is trying to iterate through the sequence x (the default behavior without interaction with numpy requested) and make each element through the iteration an R/rpy2 object. 否则,发生这种情况是因为rpy2试图遍历序列x (默认行为而不请求numpy进行交互),并使迭代中的每个元素成为R / rpy2对象。 Here it does not work because x[i] is turned to a FloatVector and you cannot have a FloatVector of FloatVector elements (you could have a list of FloatVector though). 这不起作用,因为x[i]被关到FloatVector ,你不能有一个FloatVectorFloatVector元素(你可以有FloatVector名单虽然)。 Explictly, this is what is happening (and you'll trigger the same error): 明确地说,这就是正在发生的情况(您将触发相同的错误):

FloatVector([FloatVector(y) for y in x])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM