In [1]:
import inspect
import logging
logging.root.setLevel(logging.DEBUG)

import rpy2.robjects
import rpy2.robjects.pandas2ri
import rpy2.robjects.numpy2ri
import rpy2.robjects.conversion 
from rpy2.robjects.conversion import Converter

In [2]:
code = """
data(iris)
summary(lm(Sepal.Length ~ Petal.Width, iris))
"""
summaryA = rpy2.robjects.r(code)

In [3]:
low = Converter('low')
high = Converter('high')

from rpy2.robjects.vectors import ListVector, Vector
from rpy2.rinterface import Sexp, SexpVector
def Sexp_dict(robject):
    res = {}
    for i, (key, val) in enumerate(dict(robject.slots).items()):
        # list/dict type
        if key is None or isinstance(key, rpy2.rinterface.RNULLType) :
            key = i
        # try and update objects
        try:
            res[key] = rpy2.robjects.conversion.converter.ri2py(val)
        except ValueError:
            res[key] = val
    return res


def ListVector_dict(listvector):
    res = {}
    for i, (key, val) in enumerate(listvector.items()):
        logging.debug('serializing: %s', key)
        # list/dict type
        if key is None or isinstance(key, rpy2.rinterface.RNULLType) :
            key = i
        # try and update objects
        try:
            logging.debug("serializing %s with: %s", key, rpy2.robjects.conversion.converter.ri2py.dispatch(val.__class__))
            res[key] = rpy2.robjects.conversion.converter.ri2py(val)
        except ValueError:
            logging.exception('could not convert: %s', key)
            res[key] = val
    return res
def SexpVector_list(vector):
    # don't lookup names (buggy)
    res = []
    for val in vector:
        try:
            res.append(rpy2.robjects.conversion.converter.ri2py(val))
        except ValueError:
            res.append(val)
    return res

    

high.ri2py.register(SexpVector, SexpVector_list)
high.ri2py.register(Sexp, Sexp_dict)
high.ri2py.register(ListVector, ListVector_dict)


new_converter =  high + rpy2.robjects.pandas2ri.converter + rpy2.robjects.numpy2ri.converter + rpy2.robjects.conversion.converter
rpy2.robjects.conversion.set_conversion(new_converter)

In [4]:
code = """
data(iris)
fit <- lm(Sepal.Length ~ Petal.Width, iris)
summary(fit)
"""
summary = rpy2.robjects.r(code)


DEBUG:root:serializing: call
DEBUG:root:serializing call with: <function ri2py_vector at 0x1089590d0>
DEBUG:root:serializing: terms
DEBUG:root:serializing terms with: <function ri2py_sexp at 0x108956510>
DEBUG:root:serializing: residuals
DEBUG:root:serializing residuals with: <function ri2py_vector at 0x1089590d0>
DEBUG:root:serializing: coefficients
DEBUG:root:serializing coefficients with: <function ri2py_vector at 0x1089590d0>
DEBUG:root:serializing: aliased
DEBUG:root:serializing aliased with: <function ri2py_vector at 0x1089590d0>
DEBUG:root:serializing: sigma
DEBUG:root:serializing sigma with: <function ri2py_vector at 0x1089590d0>
DEBUG:root:serializing: df
DEBUG:root:serializing df with: <function ri2py_intvector at 0x108959158>
DEBUG:root:serializing: r.squared
DEBUG:root:serializing r.squared with: <function ri2py_vector at 0x1089590d0>
DEBUG:root:serializing: adj.r.squared
DEBUG:root:serializing adj.r.squared with: <function ri2py_vector at 0x1089590d0>
DEBUG:root:serializing: fstatistic
DEBUG:root:serializing fstatistic with: <function ri2py_vector at 0x1089590d0>
DEBUG:root:serializing: cov.unscaled
DEBUG:root:serializing cov.unscaled with: <function ri2py_vector at 0x1089590d0>

In [5]:
import json
import numpy as np
def encode_difficult(obj):
    if isinstance(obj, (np.ndarray,)):
        # if it's just a scalar
        if not np.squeeze(obj).ndim:
            return np.squeeze(obj).item()
        return obj.tolist()
    elif isinstance(obj, (rpy2.rinterface.Sexp, )):
        return {'robj': repr(obj)}
    raise TypeError("%r not serializable" % (obj, ))
json.dumps(summary, default=encode_difficult)


Out[5]:
'{"fstatistic": [299.16731206935555, 1.0, 148.0], "sigma": 0.477994753562429, "adj.r.squared": 0.6667913866278083, "residuals": [0.1446545336371695, -0.055345466362838304, -0.25534546636284033, -0.35534546636284087, 0.044654533637159474, 0.266938482875887, -0.4442034917434773, 0.044654533637159474, -0.5553454663628401, 0.03351255901779612, 0.44465453363715984, -0.15534546636284072, -0.06648744098220441, -0.5664874409822044, 0.8446545336371594, 0.5669384828758869, 0.266938482875887, 0.055796508256522714, 0.6557965082565232, 0.055796508256522714, 0.44465453363715984, -0.03306151712411369, -0.35534546636284087, -0.12191954250474997, -0.15534546636284072, 0.044654533637159474, -0.13306151712411335, 0.24465453363715964, 0.24465453363715964, -0.25534546636284033, -0.15534546636284072, 0.266938482875887, 0.3335125590177959, 0.5446545336371595, -0.05534546636284018, 0.044654533637159474, 0.5446545336371595, 0.03351255901779612, -0.5553454663628401, 0.1446545336371591, -0.04420349174347693, -0.5442034917434769, -0.5553454663628401, -0.31077756788538596, -0.03306151712411369, -0.2442034917434771, 0.1446545336371591, -0.35534546636284087, 0.3446545336371593, 0.044654533637159474, 0.978358229069523, 0.28950020368888685, 0.7895002036888868, -0.4327837455498407, 0.3895002036888865, -0.23278374554984058, 0.10064217830824988, -0.7662096694079311, 0.667216254450159, -0.8216417709304769, -0.6662096694079315, -0.21049979631111315, 0.3337903305920685, 0.07835822906952261, -0.3327837455498411, 0.6783582290695231, -0.5104997963111139, 0.13379033059206827, 0.08950020368888668, -0.15506769478856838, -0.4770738724530223, 0.1672162544501589, 0.18950020368888632, 0.2560742798307954, 0.46721625445015963, 0.5783582290695226, 0.7783582290695228, 0.41178415292761394, -0.1104997963111135, 0.03379033059206862, -0.25506769478856806, -0.16620966940793158, -0.04392572016920448, -0.19935782169174995, -0.7104997963111132, -0.19935782169174995, 0.5895002036888867, 0.3672162544501591, -0.3327837455498411, -0.4327837455498407, -0.3439257201692043, 0.07835822906952261, -0.04392572016920448, -0.6662096694079315, -0.3327837455498411, -0.1439257201692041, -0.23278374554984058, 0.26721625445015945, -0.6550676947885683, -0.23278374554984058, -0.6990800501174775, -0.665931897833659, 0.4563520514050678, -0.07707387245302282, -0.23250597397556827, 0.9563520514050678, -1.388215847072386, 0.9229261275469772, 0.3229261275469775, 0.20091994988252282, -0.05478992321429534, -0.06593189783365858, 0.15635205140506794, -0.8547899232142951, -1.110222024736841, -0.421363999356204, 0.12292612754697736, 0.967494026024432, 0.8786360006437959, -0.1104997963111135, 0.07863600064379603, -0.9547899232142957, 1.1452100767857047, -0.07707387245302282, 0.05635205140506832, 0.8229261275469776, -0.17707387245302247, -0.277073872453023, -0.2436479485949315, 1.0006421783082502, 0.9340681021663415, 1.345210076785705, -0.3325059739755679, 0.18950020368888632, 0.07835822906952261, 0.8786360006437959, -0.610222024736841, 0.022926127546977707, -0.37707387245302265, 0.2563520514050685, -0.21022202473684068, 0.07863600064379603, -0.665931897833659, -0.021363999356204512, -0.2990800501174772, -0.12136399935620416, -0.16593189783365914, -0.05478992321429534, -0.6213639993562041, -0.4770738724530223], "terms": {"robj": "<RObject - Python:0x1032f2e48 / R:0x7ff92b2c9a70>"}, "call": {"robj": "<Vector - Python:0x10336db08 / R:0x7ff92b342790>\\n[RNULLType, Vector, Vector]"}, "r.squared": 0.6690276860464137, "coefficients": [[4.777629415601568, 0.07293476379886978, 65.50551707792881, 3.340431161987524e-111], [0.8885802538063636, 0.05137355130888257, 17.296453742584205, 2.325498079793244e-37]], "df": [2, 148, 2], "cov.unscaled": [[0.023282140296592594, -0.013853924649743679], [-0.013853924649743679, 0.011551354627357149]], "aliased": [0, 0]}'

In [6]:
np.squeeze(summary['adj.r.squared'])


Out[6]:
array(0.6667913866278083)

In [ ]: