3 min read

Create LaTeX, HTML and Markdown tables in R

R can do data analysis and it can create beautiful reports. You can build all these documents directly in R using rmarkdown which is powered by powerful pandoc. In lots of occasions, user just wants to get some output format of tables that we can use in other platform such as Microsoft word, LaTeX, HTML or Markdown. Here I will discuss about some packages that helps us doing so including xtable, pander, knitr, stargazer and tables. I will use a sample dataset and a summary output from a linear model fit and convert them into various format. Although each of them need their own elaborate discussion, I will just use very basics of them since one can always go and dig into the help file for any details.

xtable::print.xtable(
  xtable::xtable(mtcars), type = 'html'
)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.00 6.00 160.00 110.00 3.90 2.62 16.46 0.00 1.00 4.00 4.00
Mazda RX4 Wag 21.00 6.00 160.00 110.00 3.90 2.88 17.02 0.00 1.00 4.00 4.00
Datsun 710 22.80 4.00 108.00 93.00 3.85 2.32 18.61 1.00 1.00 4.00 1.00
Hornet 4 Drive 21.40 6.00 258.00 110.00 3.08 3.21 19.44 1.00 0.00 3.00 1.00
Hornet Sportabout 18.70 8.00 360.00 175.00 3.15 3.44 17.02 0.00 0.00 3.00 2.00
pander::pander(mtcars)
Table continues below
  mpg cyl disp hp drat wt qsec vs
Mazda RX4 21 6 160 110 3.9 2.62 16.46 0
Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0
Datsun 710 22.8 4 108 93 3.85 2.32 18.61 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1
Hornet Sportabout 18.7 8 360 175 3.15 3.44 17.02 0
  am gear carb
Mazda RX4 1 4 4
Mazda RX4 Wag 1 4 4
Datsun 710 1 4 1
Hornet 4 Drive 0 3 1
Hornet Sportabout 0 3 2
knitr::kable(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
tables::as.tabular(mtcars)
                                                                     
                   mpg  cyl disp hp  drat wt    qsec  vs am gear carb
 Mazda RX4         21.0 6   160  110 3.90 2.620 16.46 0  1  4    4   
 Mazda RX4 Wag     21.0 6   160  110 3.90 2.875 17.02 0  1  4    4   
 Datsun 710        22.8 4   108   93 3.85 2.320 18.61 1  1  4    1   
 Hornet 4 Drive    21.4 6   258  110 3.08 3.215 19.44 1  0  3    1   
 Hornet Sportabout 18.7 8   360  175 3.15 3.440 17.02 0  0  3    2   

Exercise

  1. Use the mtcars dataset, fit a linear model with mpg as response variable and wt,hp and disp as predictor variable. Generate a LaTeX table and HTML table for the fitted model using xtable.