Question

I can get the output I need using R, but I can not reproduce within python's rpy2 module.

In R:

> wilcox.test(c(1,2,3), c(100,200,300), alternative = "less")$p.value

gives

[1] 0.05

In python:

import rpy2.robjects as robjects
rwilcox = robjects.r['wilcox.test']
x = robjects.IntVector([1,2,3,])
y = robjects.IntVector([100,200,300])
z = rwilcox(x,y, alternative = "less")
print z

gives:

Wilcoxon rank sum test  
data:  1:3 and c(100L, 200L, 300L)  
W = 0, p-value = 0.05  
alternative hypothesis: true location shift is less than 0 

And:

z1 = z.rx('p.value')
print z1

gives:

$p.value  
[1] 0.05

Still trying to get a final value of 0.05 stored as a variable, but this seems to be closer to a final answer.

I am unable to figure out what my python code needs to be to to store the p.value in a new variable.

Was it helpful?

Solution 2

Just using list() ?

pval = z.rx2('p-value')
print list(pval) # [0.05]

rpy2 also works well with numpy:

import numpy
pval = numpy.array(pval)
print pval       # array([ 0.05])

http://rpy.sourceforge.net/rpy2/doc-2.3/html/numpy.html#from-rpy2-to-numpy

OTHER TIPS

z1 is a ListVector containing one FloatVector with one element:

>>> z1
<ListVector - Python:0x4173368 / R:0x36fa648>
[FloatVector]
  p.value: <class 'rpy2.robjects.vectors.FloatVector'>
  <FloatVector - Python:0x4173290 / R:0x35e6b38>
[0.050000]

You can extract the float itself with z1[0][0] or just float(z1[0]):

>>> z1[0][0]
0.05
>>> type(z1[0][0])
<type 'float'>
>>> float(z1[0])
0.05

In general you are going to have an easier time figuring out what is going on in an interactive session if you just supply the name of the object you want a representation of. Using print x statement transforms things through str(x) when the repr(x) representation used implicitly by the interactive loop is much more helpful. If you are doing things in a script, use print repr(x) instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top