Search code examples
rxtablegridextra

Rendering xtable with significant digits


I'd like to be able to render an xtable in an automatically run piece of code, i.e. NOT via copy-and-paste, while controlling the number of significant digits. The only way that I know to render an xtable on a standard plot device is by using grid.table, but that method ignores the digits directive and plots all available digits. Here's a code example. Any advice?

library(xtable)
library(gridExtra)

x = rnorm(100)
y = x + rnorm(100)
m = lm(y ~ x)

print(xtable(m)) #too many decimal places
print(xtable(m, digits = 2)) #this works
grid.table(xtable(m, digits=2)) #this doesn't!!!

None of the bits of advice here seem useful for automated rendering: R: rendering xtable


Solution

  • If you convert everything to strings, you should be able to make this work:

    x <- xtable(m)
    x[] <- lapply(x, sprintf, fmt = "%0.2f")
    grid.table(x)
    

    enter image description here