使用 rpy2 将 R 对象转换为 Python 对象
问题:如何将 R 对象转换为 python 对象
我的情况:我需要将 cor.test() 的结果使用到 python 例程中。
correlation = robjects.r('function(x, y) cor.test(x, y)')
corr= correlation(robjects.IntVector(goodtotemp), robjects.IntVector(goodGDPs))
print corr
print corr[3]
print 'coef:',type(corr[3])
输出,如预期:
cor
0.984881
coef: <class 'rpy2.robjects.vectors.FloatVector'>
然而,我不能使用 corr[3] 作为 python 对象,
c=corr[3]
print 'c:',c*10., type(c)
看看(这是我如何知道我做错了什么!),输出:
c:
Traceback (most recent call last):
File "./GDPAnalyzer.py", line 234, in <module>
print 'c:',c*10., type(c)
TypeError: unsupported operand type(s) for *: 'FloatVector' and 'float'
任何提示/帮助都值得赞赏!
The question: how to cast R objects to python ones
My case: I need to use the result of cor.test() into a python routine.
correlation = robjects.r('function(x, y) cor.test(x, y)')
corr= correlation(robjects.IntVector(goodtotemp), robjects.IntVector(goodGDPs))
print corr
print corr[3]
print 'coef:',type(corr[3])
outputs, as expected:
cor
0.984881
coef: <class 'rpy2.robjects.vectors.FloatVector'>
Howover, I can't use corr[3] as an python object,
c=corr[3]
print 'c:',c*10., type(c)
look (Here's how I know that I'm doing something wrong!), the output:
c:
Traceback (most recent call last):
File "./GDPAnalyzer.py", line 234, in <module>
print 'c:',c*10., type(c)
TypeError: unsupported operand type(s) for *: 'FloatVector' and 'float'
Any hint/help is appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
分段错误应该作为 rpy2 bug 报告。否则,请尝试:
或:
The segmentation fault is a something that should be reported as an rpy2 bug. Otherwise, try either:
or:
Python 确实不支持
类型转换
的概念。确实,在某些有限的情况下,它确实会执行诸如使用内置类型进行强制转换之类的操作。但除此之外,程序员还可以将对象从一种形式转换为另一种形式,或者创建某种形式的外观或填充对象,使 R 对象的行为类似于 Python 对象。
尝试
print type(corr[3])
查看正在使用的 Python 类型。它可能只是数字的字符串表示形式,在这种情况下,您可以使用 eval() 将其转换为浮点数。Python really does not support the concept of
casting
. It's true that in some limited circumstances it does do something like casting with built-in types.But beyond that it is up to the programmer to CONVERT objects from one form to another or to create some form of facade or shim object that makes the R object behave like a Python one.
Try
print type(corr[3])
to see what Python type is being used. It might just be a string representation of the number, in which case you could useeval()
to convert it to a float.