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!
The segmentation fault is a something that should be reported as an rpy2 bug. Otherwise, try either:
c.ro * 3
or:
c[0] * 3
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 use eval()
to convert it to a float.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.