Question

I am running a few linear model fits in python (using R as a backend via RPy) and I would like to export some LaTeX tables with my R "summary" data.

This thread explains quite well how to do it in R (with the xtable function), but I cannot figure out how to implement this in RPy.

The only relevant thing searches such as "Chunk RPy" or "xtable RPy" returned was this, which seems to load the package in python but not to use it :-/

Here's an example of how I use RPy and what happens.

And this would be the error without bothering to load any data:

from rpy2.robjects.packages import importr
xtable = importr('xtable')
latex = xtable('')

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-131-8b38f31b5bb9> in <module>()
----> 1 latex = xtable(res_sum)
  2 print latex

TypeError: 'SignatureTranslatedPackage' object is not callable

I have tried using the stargazer package instead of xtable and I get the same error.

Was it helpful?

Solution

Ok, I solved it, and I'm a bit ashamed to say that it was a total no-brainer.

You just have to call the functions as xtable.xtable() or stargazer.stargazer().

OTHER TIPS

To easily generate TeX data from Python, I wrote the following function;

import re


def tformat(txt, v):
    """Replace the variables between [] in raw text with the contents
    of the named variables. Between the [] there should be a variable name,
    a colon and a formatting specification. E.g. [smin:.2f] would give the
    value of the smin variable printed as a float with two decimal digits.

    :txt: The text to search for replacements
    :v: Dictionary to use for variables.
    :returns: The txt string with variables substituted by their formatted
    values.
    """
    rx = re.compile(r'\[(\w+)(\[\d+\])?:([^\]]+)\]')
    matches = rx.finditer(txt)
    for m in matches:
        nm, idx, fmt = m.groups()
        try:
            if idx:
                idx = int(idx[1:-1])
                r = format(v[nm][idx], fmt)
            else:
                r = format(v[nm], fmt)
            txt = txt.replace(m.group(0), r)
        except KeyError:
            raise ValueError('Variable "{}" not found'.format(nm))
    return txt

You can use any variable name from the dictionary in the text that you pass to this function and have it replaced by the formatted value of that variable.

What I tend to do is to do my calculations in Python, and then pass the output of the globals() function as the second parameter of tformat:

smin = 235.0
smax = 580.0
lst = [0, 1, 2, 3, 4]
t = r'''The strength of the steel lies between SI{[smin:.0f]}{MPa} and \SI{[smax:.0f]}{MPa}. lst[2] = [lst[2]:d].'''
print tformat(t, globals())

Feel free to use this. I put it in the public domain.

Edit: I'm not sure what you mean by "linear model fits", but might numpy.polyfit do what you want in Python?

To resolve your problem, please update stargazer to version 4.5.3, now available on CRAN. Your example should then work perfectly.

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