1

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.

Community
  • 1
  • 1
TheChymera
  • 17,004
  • 14
  • 56
  • 86

3 Answers3

1

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().

TheChymera
  • 17,004
  • 14
  • 56
  • 86
  • That's right. `importr()` imports an R _package_ (http://rpy.sourceforge.net/rpy2/doc-dev/html/robjects_rpackages.html#rpy2.robjects.packages.importr), and R _functions_ live in packages. Here the the R package `xtable` defines the function `xtable`. In R, the explicit way to call it would be `xtable::xtable()`. – lgautier Nov 10 '13 at 21:34
  • what about [texreg](http://cran.r-project.org/web/packages/texreg/index.html)? I'm trying to run the extract.lme4() function from it and [no way of calling it seems to work](http://nbviewer.ipython.org/urls/gist.github.com/TheChymera/7396334/raw/52783c65e0fa752fd142b819f6fa4b43b9f222fd/nlme-aov). – TheChymera Nov 11 '13 at 06:53
  • surprize surprize, "extract" is called by texreg implicity so texreg also works as texreg.texreg(). Please excuse all the confusion. – TheChymera Nov 12 '13 at 12:12
0

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?

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • I'd like to thank you for sharing your code - but how does this relate to my use case? I'd like to use xtable (or any other method which can deal well with R summary data). This pertains especially to multiindexed tables, which I do not see any support for in your code. – TheChymera Nov 10 '13 at 15:59
  • @TheChymera My thoughts were that if you can get the data from R to python this code could help create LaTeX from it. My number crunching needs are generally well-met by numpy, so I've never used R yet. – Roland Smith Nov 10 '13 at 17:11
  • Pandas provides a very nice `.to_latex()` method - which may also be interesting for you. python to latex is no issue for me. It's rather getting stuff out of R which is problematic, which is why my question was very R-centric. – TheChymera Nov 10 '13 at 17:16
  • @TheChymera A quick look at the docs show that the `Robj` has a specific conversion [method](http://rpy.sourceforge.net/rpy/doc/rpy_html/Methods-of-Robj-type.html#Methods-of-Robj-type). And there is a [sequence protocol](http://rpy.sourceforge.net/rpy/doc/rpy_html/Sequence-protocol.html#Sequence-protocol). But I guess those won't work with your data? – Roland Smith Nov 10 '13 at 17:33
  • I have not been able to go from R summary to R dataframe to Pandas dataframe to LaTeX, no. But I may open up a question on the very many issues down that road IF the simpler RPy to LaTeX approach cannot be implemented because of how xtable or stargazer run under RPy. – TheChymera Nov 10 '13 at 17:43
0

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

  • many thanks for your input, but this is not the issue I asked you about in my email (this was about how to call R library functions - for example xtable or stargazer from RPy). as you can see in my own answer, this was resolved quite easily. – TheChymera Nov 15 '13 at 12:17