为 rpy2 转换 python 对象 [英] Converting python objects for rpy2
问题描述
下面的代码应该在 rpy2 中创建一个热图
The following code is supposed to create a heatmap in rpy2
import numpy as np
from rpy2.robjects import r
data = np.random.random((10,10))
r.heatmap(data)
然而,它导致以下错误
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.
从文档中我了解到 r.heatmap 需要数字矩阵".如何将 np.array 转换为所需的数据类型?
From the documentation I learn that r.heatmap expects "a numeric matrix". How do I convert np.array to the required data type?
推荐答案
需要添加
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
在 rpy2 文档中查看更多信息numpy 部分(此处 用于较旧的 2.x 版本)
See more in rpy2 documentation numpy section (here for the older 2.x version)
在 2.2.x 之前,仅导入就足够了.
Prior to 2.2.x the import alone was sufficient.
仅导入就足以切换自动转换将 numpy 对象转换为 rpy2 对象.
That import alone is sufficient to switch an automatic conversion of numpy objects into rpy2 objects.
为什么将其设为可选导入,虽然它可以被包含在函数 py2ri() (如在为此提交的原始补丁函数)?
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) ?
虽然两者都是有效且合理的选项,已做出设计决定为了将 rpy2 与 numpy 解耦最多,不要假设已自动安装 numpy意味着程序员想要使用
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.
这篇关于为 rpy2 转换 python 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!