0

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

Community
  • 1
  • 1
rimorob
  • 624
  • 1
  • 5
  • 16
  • Do you need to render it on a plot device? – Thomas Feb 23 '16 at 21:37
  • yes, I do. I could probably find work-arounds for rendering to pdf, but that's not enough. I need to be able to render to either one. – rimorob Feb 23 '16 at 21:38
  • `xtable` produces a data.frame with further attributes that are used for formatting when printing to latex or html formats. `grid.table` ignores them altogether and only deals with the bare data.frame, so any number formatting has to be done on the data itself, e.g. with `sprintf` or `formatC` – baptiste Feb 24 '16 at 07:58

2 Answers2

2

I'm not sure of your final plot device, but for some purposes you can just skip xtable all together:

library("broom")
library("gridExtra")
x = rnorm(100)
y = x + rnorm(100)
m = lm(y ~ x)
DF <- broom::tidy(m)
DF[,2:4] <- round(DF[,2:4], 2)
DF[,5] <- format(DF[,5], scientific = TRUE, digits = 4)
grid.table(DF)

Make sure you have the latest gridExtra. You can also control the appearance of the table in great detail, via themes (there is a vignette on the topic).

Bryan Hanson
  • 6,055
  • 4
  • 41
  • 78
2

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

Thomas
  • 43,637
  • 12
  • 109
  • 140