rimorob
rimorob

Reputation: 654

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

Upvotes: 0

Views: 554

Answers (2)

Thomas
Thomas

Reputation: 44525

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

Upvotes: 2

Bryan Hanson
Bryan Hanson

Reputation: 6213

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

Upvotes: 2

Related Questions