0
votes

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

2
Do you need to render it on a plot device?Thomas
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
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 formatCbaptiste

2 Answers

2
votes

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

2
votes

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