RRRR 9. Showing Results with Tables

Solange Mongoue

September 7, 2016

Outline

Learn how to dynamically connect statistical results with tables in your presentation documents written in LaTeX and Markdown

Focus on three tools in this chapter:

Basic knitr Syntax for Tables

results option is the most important chunk option

4 values

Tables in LaTeX

The center environment

\begin{center}

  This is a center environment.    
  
\end{center}   

The tabular environment

To begin, type \begin{tabular}{TABLE_SPEC}.

{TABLE_SPEC} allows you to specify the number of columns and the text alignment in each column.

Example: to create a table with three columns, the first is left-justified and the latter two are center-justified, type

\begin{tabular}{l | c c}

Full laTeX code

\begin{tabular}{l | c c}
  \hline
  Observation & Variable1 & Variable2 \\
  \hline \hline
  Subject1 & a & b \\
  Subject2 & c & d \\
  Subject3 & e & f \\
  Subject4 & g & h \\
  \hline
\end{tabular}

Tables in LaTeX

The table float environment

Allows us to separate a table from the text, specify its location and give it a caption.

LaTeX code

\begin{table}[t]
    \caption{Example Simple LaTeX Table}
    \label{ExLaTeXTable}
    \begin{center}
      \begin{tabular}{l | c c}
        \hline
        Observation & Variable1 & Variable2 \\
        \hline \hline
        Subject1 & a & b \\
        Subject2 & c & d \\
        Subject3 & e & f \\
        Subject4 & g & h \\
        \hline
      \end{tabular}
    \end{center}
\end{table}

Tables in Markdown/HTML

Markdown tables

Example: this code will create the left-center-center justified formatted table

### Example Simple Markdown Table
Observation | Variable1 | Variable2
----------- | --------- | ---------
Subject1    | a         | b
Subject2    | c         | d
Subject3    | e         | f
Subject4    | g         | c

Example Simple Markdown Table

Observation Variable1 Variable2
Subject1 a b
Subject2 c d
Subject3 e f
Subject4 g c

Tables in Markdown/HTML

HTML tables

Example: Recreate the same left-center-center justified formatted table

<table>
  <thead>
    <tr>
        <td>Observation</td> <td>Variable1</td> <td>Variable2</td>
    </tr>
  </thead>
  <tbody>
    <tr>
        <td>Subject1</td> <td>a</td> <td>b</td>
    </tr>
    <tr>
        <td>Subject2</td> <td>c</td> <td>d</td>
    </tr>
    <tr>
        <td>Subject3</td> <td>e</td> <td>e</td>
    </tr>
    <tr>
        <td>Subject4</td> <td>f</td> <td>f</td>
    </tr>
  </tbody>
</table>
Observation Variable1 Variable2
Subject1 a b
Subject2 c d
Subject3 e e
Subject4 f f

Creating Tables from Supported Class R Objects

Use kable funtion, xtable and texreg packages.

They work easily with specific object classess that their designers explicitly support.

kable for Markdown and LaTeX

Converts matrices and data frames into tables for Markdown, HTML and LaTeX

kable_ex <- data.frame(
            Observation = c("Subject1", "Subject2",
                            "Subject3", "Subject4"),
            Variable1 = c("a", "c", "e", "g"),
            Variable2 = c("b", "d", "f", "c")
)
kable(kable_ex, caption = "Example kable Table", format = "markdown")
Observation Variable1 Variable2
Subject1 a b
Subject2 c d
Subject3 e f
Subject4 g c

Creating Tables from Supported Class R Objects

xtable for LaTeX and HTML

# Fit simple linear regression model
M1 <- lm(Examination ~ Education, data = swiss)
# Show M1 class
class(M1)
## [1] "lm"
# Show summary of M1 model object
summary(M1)
## 
## Call:
## lm(formula = Examination ~ Education, data = swiss)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -10.9322  -4.7633  -0.1838   3.8907  12.4983 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 10.12748    1.28589   7.876 5.23e-10 ***
## Education    0.57947    0.08852   6.546 4.81e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.773 on 45 degrees of freedom
## Multiple R-squared:  0.4878, Adjusted R-squared:  0.4764 
## F-statistic: 42.85 on 1 and 45 DF,  p-value: 4.811e-08
library(xtable)
methods(xtable)

[1] xtable.anova* xtable.aov*
[3] xtable.aovlist* xtable.coxph*
[5] xtable.data.frame* xtable.glm*
[7] xtable.gmsar* xtable.lagImpact*
[9] xtable.lm* xtable.matrix*
[11] xtable.prcomp* xtable.sarlm*
[13] xtable.sarlm.pred* xtable.spautolm*
[15] xtable.sphet* xtable.splm*
[17] xtable.stsls* xtable.summary.aov*
[19] xtable.summary.aovlist* xtable.summary.glm*
[21] xtable.summary.gmsar* xtable.summary.lm*
[23] xtable.summary.prcomp* xtable.summary.sarlm*
[25] xtable.summary.spautolm* xtable.summary.sphet*
[27] xtable.summary.splm* xtable.summary.stsls*
[29] xtable.table* xtable.ts*
[31] xtable.zoo*
see ‘?methods’ for accessing help and source code

Creating Tables from Supported Class R Objects

xtable for LaTeX

Let’s create a table summarizing the estimates from the M1 model obsject. The code below will generate the LaTeX syntax.

# Load xtable
library(xtable)

# Create LaTeX table from M1 and show the output markup
xtable(M1, caption = "Linear Regression,
        Dependent Variable: Exam Score",
        label = "BasicXtableSummary",
        digits = 1)
## % latex table generated in R 3.3.1 by xtable 1.8-2 package
## % Wed Sep 07 15:09:12 2016
## \begin{table}[ht]
## \centering
## \begin{tabular}{rrrrr}
##   \hline
##  & Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\ 
##   \hline
## (Intercept) & 10.1 & 1.3 & 7.9 & 0.0 \\ 
##   Education & 0.6 & 0.1 & 6.5 & 0.0 \\ 
##    \hline
## \end{tabular}
## \caption{Linear Regression,
##         Dependent Variable: Exam Score} 
## \label{BasicXtableSummary}
## \end{table}

Creating Tables from Supported Class R Objects

xtable for Markdown/HTML

# Load xtable
library(xtable)
# Create an xtable object from M1
M1Table <- xtable(M1, caption = "Linear Regression, Dependent
                      Variable: Exam Score",
                      label = "BasicXtableSummary",
                      digits = 1)
# Create HTML summary table of M1Table
print.xtable(M1Table, type = "html", caption.placement = "top")
Linear Regression, Dependent Variable: Exam Score
Estimate Std. Error t value Pr(>|t|)
(Intercept) 10.1 1.3 7.9 0.0
Education 0.6 0.1 6.5 0.0

Creating Tables from Supported Class R Objects

texreg for LaTeX and HTML

# Estimated nested regression models
M1 <- lm(Examination ~ Education, data = swiss)
M2 <- lm(Examination ~ Education + Agriculture, data = swiss)
M3 <- lm(Examination ~ Education + Agriculture + Catholic, data = swiss)
M4 <- lm(Examination ~ Education + Agriculture + Catholic + Infant.Mortality, data = swiss)
M5 <- lm(Examination ~ Education + Agriculture + Catholic + Infant.Mortality + Fertility, data = swiss)

textreg for LaTex

# Load texreg package
library(texreg)
## Version:  1.36.7
## Date:     2016-06-21
## Author:   Philip Leifeld (University of Glasgow)
## 
## Please cite the JSS article in your publications -- see citation("texreg").
# Create custom coefficient names
cust_coef <- c('(Intercept)', 'Education', 'Agriculture', 'Catholic', 'Infant Mortality','Fertility')
# Create nested regression model table
texreg(list(M1, M2, M3, M4, M5),
      caption = 'Nested Estimates Table with \\emph{texreg}',
      caption.above = TRUE,
      label = 'Basic_texregTable',
      custom.coef.names = cust_coef)
## 
## \begin{table}
## \caption{Nested Estimates Table with \emph{texreg}}
## \begin{center}
## \begin{tabular}{l c c c c c }
## \hline
##  & Model 1 & Model 2 & Model 3 & Model 4 & Model 5 \\
## \hline
## (Intercept)      & $10.13^{***}$ & $19.72^{***}$ & $18.54^{***}$ & $18.66^{**}$  & $24.57^{**}$ \\
##                  & $(1.29)$      & $(3.20)$      & $(2.64)$      & $(5.84)$      & $(8.24)$     \\
## Education        & $0.58^{***}$  & $0.36^{**}$   & $0.42^{***}$  & $0.42^{***}$  & $0.33^{*}$   \\
##                  & $(0.09)$      & $(0.10)$      & $(0.09)$      & $(0.09)$      & $(0.13)$     \\
## Agriculture      &               & $-0.14^{**}$  & $-0.07$       & $-0.07$       & $-0.08$      \\
##                  &               & $(0.04)$      & $(0.04)$      & $(0.04)$      & $(0.04)$     \\
## Catholic         &               &               & $-0.08^{***}$ & $-0.08^{***}$ & $-0.07^{**}$ \\
##                  &               &               & $(0.02)$      & $(0.02)$      & $(0.02)$     \\
## Infant Mortality &               &               &               & $-0.01$       & $0.10$       \\
##                  &               &               &               & $(0.23)$      & $(0.25)$     \\
## Fertility        &               &               &               &               & $-0.10$      \\
##                  &               &               &               &               & $(0.09)$     \\
## \hline
## R$^2$            & 0.49          & 0.59          & 0.73          & 0.73          & 0.73         \\
## Adj. R$^2$       & 0.48          & 0.57          & 0.71          & 0.70          & 0.70         \\
## Num. obs.        & 47            & 47            & 47            & 47            & 47           \\
## RMSE             & 5.77          & 5.25          & 4.30          & 4.36          & 4.35         \\
## \hline
## \multicolumn{6}{l}{\scriptsize{$^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$}}
## \end{tabular}
## \label{Basic_texregTable}
## \end{center}
## \end{table}

textreg for HTML

library (texreg)
htmlreg(list(M1, M2, M3, M4, M5),
        caption = 'Nested Estimates Table in HTML Document',
        caption.above = TRUE,
        custom.coef.names = cust_coef)
Nested Estimates Table in HTML Document
Model 1 Model 2 Model 3 Model 4 Model 5
(Intercept) 10.13*** 19.72*** 18.54*** 18.66** 24.57**
(1.29) (3.20) (2.64) (5.84) (8.24)
Education 0.58*** 0.36** 0.42*** 0.42*** 0.33*
(0.09) (0.10) (0.09) (0.09) (0.13)
Agriculture -0.14** -0.07 -0.07 -0.08
(0.04) (0.04) (0.04) (0.04)
Catholic -0.08*** -0.08*** -0.07**
(0.02) (0.02) (0.02)
Infant Mortality -0.01 0.10
(0.23) (0.25)
Fertility -0.10
(0.09)
R2 0.49 0.59 0.73 0.73 0.73
Adj. R2 0.48 0.57 0.71 0.70 0.70
Num. obs. 47 47 47 47 47
RMSE 5.77 5.25 4.30 4.36 4.35
p < 0.001, p < 0.01, p < 0.05

Creating Variable Description documents with xtable

# Create variable vector from column names
Variable <- names(swiss)

# Create variable description vector
Description <- c("common standardized fertility measures",
"% of males involved in agriculture as occupation",
"% draftees receiving highest mark on army examination",
"% education beyond primary school for draftees",
"% 'catholic' (as opposed to 'protestant')",
"% live births who live less-than 1 year"
)

# Combine Variable and Description variables into a matrix
DescriptionsBound <- cbind(Variable, Description)

# Create an xtable object from DescriptionsBound
DescriptionsTable <- xtable(DescriptionsBound)

# Format table in HTML
DescriptTable <- print.xtable(DescriptionsTable, type = "html")
Variable Description
1 Fertility common standardized fertility measures
2 Agriculture % of males involved in agriculture as occupation
3 Examination % draftees receiving highest mark on army examination
4 Education % education beyond primary school for draftees
5 Catholic % ‘catholic’ (as opposed to ‘protestant’)
6 Infant.Mortality % live births who live less-than 1 year
# Create variable description file
cat("# Swiss Data Variable Descriptions \n",
    "### Source: Mosteller and Tukey, (1977) \n",
    DescriptTable,
    file = "SwissVariableDescriptions.md"
)