为 rpy2 转换 python 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2447454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting python objects for rpy2
提问by Boris Gorelik
The following code is supposed to create a heatmap in rpy2
下面的代码应该在 rpy2 中创建一个热图
import numpy as np
from rpy2.robjects import r
data = np.random.random((10,10))
r.heatmap(data)
However, it results in the following error
但是,它导致以下错误
Traceback (most recent call last):
File "z.py", line 8, in <module>
labRow=rowNames, labCol=colNames)
File "C:\Python25\lib\site-packages\rpy2\robjects\__init__.py", line 418, in __call__
new_args = [conversion.py2ri(a) for a in args]
File "C:\Python25\lib\site-packages\rpy2\robjects\__init__.py", line 93, in default_py2ri
raise(ValueError("Nothing can be done for the type %s at the moment." %(type(o))))
ValueError: Nothing can be done for the type <type 'numpy.ndarray'> at the moment.
From the documentation I learn that r.heatmap expects "a numeric matrix". How do I convert np.array to the required data type?
从文档中我了解到 r.heatmap 需要“数字矩阵”。如何将 np.array 转换为所需的数据类型?
回答by unutbu
You need to add
你需要添加
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
See more in rpy2 documentation numpy section(herefor the older 2.x version)
在 rpy2 文档numpy 部分查看更多信息(这里是旧的 2.x 版本)
Prior to 2.2.x the import alone was sufficient.
在 2.2.x 之前,仅导入就足够了。
That import alone is sufficient to switch an automatic conversion of numpy objects into rpy2 objects.
Why make this an optional import, while it could have been included in the function py2ri() (as done in the original patch submitted for that function) ?
Although both are valid and reasonable options, the design decision was taken in order to decouple rpy2 from numpy the most, and do not assume that having numpy installed automatically meant that a programmer wanted to use it.
仅导入就足以将 numpy 对象自动转换为 rpy2 对象。
为什么将其设为可选导入,而它可能已包含在函数 py2ri() 中(如为该函数提交的原始补丁中所做的那样)?
尽管两者都是有效且合理的选择,但设计决策是为了最大限度地将 rpy2 与 numpy 分离,并且不要假设自动安装 numpy 意味着程序员想要使用它。
回答by brink
For rpy2 2.2.4 I had to add:
对于 rpy2 2.2.4,我必须添加:
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
回答by flinz
For me (2.2.1) the following also worked (as documented on http://rpy.sourceforge.net/rpy2/doc-2.2/html/numpy.html):
对我(2.2.1)来说,以下内容也有效(如http://rpy.sourceforge.net/rpy2/doc-2.2/html/numpy.html 上所述):
import rpy2.robjects as ro
from rpy2.robjects.numpy2ri import numpy2ri
ro.conversion.py2ri = numpy2ri