Sending data from Python to R to perform statistical test using rpy2
Question: I want to use the [Fisher's exact test
functionality](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/fisher.test.html)
(specifically, the MC simulation functionality) of R with an interface to
Python. I'm trying to do that using
[rpy2](http://rpy.sourceforge.net/rpy2/doc-dev/html/introduction.html), but
it's more difficult than I thought.

I can get an interface to the Fisher's test method using the following code:

    
    
    import rpy2.robjects as robjects
    fisher = robjects.r['fisher.test']
    

However, how do I pass a `2xN` matrix to the function and retrieve the
p-value?


Answer: Consider importing R's stats package and run the Fisher Test as a Python
function. Do note, the `result` object is `<class
'rpy2.robjects.vectors.ListVector'>` and hence must be converted to a Python
dictionary as shown below.

    
    
    import rpy2
    from rpy2.robjects.numpy2ri import numpy2ri
    from rpy2.robjects.packages import importr
    import numpy as np
    
    cont = np.reshape(np.arange(0,4), (2,2))
    
    statspackage = importr('stats',  robject_translations={'format_perc': '_format_perc'})    
    result = statspackage.fisher_test(numpy2ri(cont), simulate_p_value = True, B = 100)
    
    # DEPRECATED CONVERSION
    import pandas.rpy.common as com
    pyresultdict = com.convert_robj(result)
    
    for k, v in  pyresultdict.items():
        print(k, v)
    
    # data.name ['structure(c(0L, 2L, 1L, 3L), .Dim = c(2L, 2L))']
    # p.value [1.0]
    # estimate odds ratio    0.0
    # dtype: float64
    # null.value odds ratio    1.0
    # dtype: float64
    # conf.int [0.0, 77.90626902008512]
    # alternative ['two.sided']
    # method ["Fisher's Exact Test for Count Data"]
    

* * *

Another note, you may receive a warning about the deprecation of
`com.convert_to_r_dataframe` and `com.convert_robj(rdf)` which should be
replaced with `pandas2ri.pandas2ri()` and `pandas2ri` as suggested
[here](http://pandas.pydata.org/pandas-docs/stable/r_interface.html). However,
the conversion on my end does not work for the _ListVector_ object. Ideally,
above conversion would be replaced with below:

    
    
    # CURRENT CONVERSION
    from rpy2.robjects import pandas2ri
    pandas2ri.activate()
    pyresultdict = pandas2ri.ri2py(result)
    
    for k, v in  pyresultdict.items():
        print(k, v)
    

