52
14
texreg: Conversion of R Model Output to L
A
T
E
Xand HTML
to create professional horizontal rules. These arguments can be omitted if the two packages
are not available (in this case, top, mid and bottom rules are replaced by conventional hor-
izontal rules, and numeric values are horizontally aligned at the center of the column). The
\usepackage{} declarations for the two packages are suppressed because the code has to be
processed by Sweave().
In order to omit the \begin{table} and \end{table} as well as the \begin{center} and
\end{center} code, the table and center arguments can be used. If table = FALSE and
center = FALSE are set, only the tabular environment is printed, not the table and center
environments. In eect, the resulting table would be printed in-line in the text. Another
reason for skipping the table environment could be to netune the environment manually.
Alternatively, the argument sideways = TRUE can be used to rotate the table by 90 degrees
using the sidewaystable environment in the rotating package (RahtzandFairbairns2008)
instead of the default table environment.
5.3. Custom names, omission of terms, and customization of coecients
Another example demonstrates how the LAT
E
Xcode can be saved in an object The result is
shown in Table4.
R> mytable <- texreg(list(m1, m2), label = "tab:4",
+
caption = "Bolded coefficients, custom notes, three digits.",
+
float.pos = "h", bold = 0.05, stars = 0, custom.note =
+
"Coefficients with $p < 0.05$ in \\textbf{bold}.",
+
digits = 3, leading.zero = FALSE, omit.coef = "Inter")
The table can be printed to the R console later by calling the name of the object (in this case
mytable).
The example presented above introduced several additional arguments: bold = 0.05 formats
all coecients with p values < 0:05 in bold; stars = 0 means that only coecients with
p values < 0 are decorated with a star, which eectively suppresses all signicance stars
in the table because negative p values are not possible. Note that bold formatting cannot
be used in combination with the dcolumn argument, so decimal mark alignment is switched
o in Table 4. The booktabs argument was also left out to show the dierence between
conventional horizontal lines in Table4 and booktabs rules in Table3. The custom.note =
"Coefficients with $p < 0.05$ in bold." argument changes the signicance note below
the table. The digits = 3 argument sets three decimal places, leading.zero = FALSE
suppresses leading zeroes before the decimal separator, and omit.coef = "Inter" causes
all rows containing the regular expression\Inter" to be skipped from the output (here: the
\(Intercept)" term). Note that more complex regular expressions are possible; for example,
omit.coef = "(Trt)|(Ctl)" would remove all rows matching either \Trt"or \Ctl".
5.4. Multiple model types, single.row, and custom names
Another example shows how texreg can deal with multiple kinds of models in the same table.
The following code shows how ordinary least squares (OLS) and generalized least squares
(GLS) models are matched in a single output table. The output is shown in Table5.
77
Philip Leifeld
15
R> library("nlme")
R> m3 <- gls(follicles ~ sin(2 * pi * Time) + cos(2 * pi * Time), Ovary,
+
correlation = corAR1(form = ~ 1 | Mare))
R> texreg(
+
list(m1, m3),
+
custom.coef.names = c(
+
"Intercept",
+
"Control",
+
"$\\sin(2 \\cdot \\pi \\cdot \\mbox{time})$",
+
"$\\cos(2 \\cdot \\pi \\cdot \\mbox{time})$"
+
),
+
custom.model.names = c("OLS model", "GLS model"),
+
reorder.coef = c(1, 3, 4, 2),
+
caption = "Multiple model types, custom names, and single row.",
+
label = "tab:5",
+
stars = c(0.01, 0.001),
+
dcolumn = TRUE,
+
booktabs = TRUE,
+
use.packages = FALSE,
+
single.row = TRUE,
+
include.adjrs = FALSE,
+
include.bic = FALSE
+ )
Several interesting things can be noted. First, the custom.coef.names argument was used to
relabel the coecient rows.
If there were repetitions of coecient names in the
custom.coef.names vector, texreg would try to con
ate rows with identical names. In the
case shown here, the two models are only matched on the intercept and the number of obser-
vations because all other rows have unique names.
Second, the custom names include L
A
T
E
Xcode. Within the code, in-line math code is allowed.
L
A
T
E
Xcommands have to be marked by an additional backslash as an escape character, e.g.,
\\pi instead of \pi. Text within math blocks can be included in \mbox{} commands.
Third, custom names were also provided for the models. Using the custom.model.names
argument, the default \Model 1", \Model 2" etc. are replaced by \OLS model" and \GLS
model" in this case.
Fourth, the order of the coecients was changed using the reorder.coef argument. The
\Control" term was moved to the last position in the table.
Fifth, two signicance levels (and, accordingly, a maximum of two stars) are used in the table.
The stars argument takes at most four values, and when four values are specied, the lowest
signicance level (usually 0:05 p < 0:1) is denoted by the character specied in the symbol
argument (by default a centered dot).
Sixth, the single.row argument causes the table to consume less vertical and more horizontal
space because the standard errors are inserted right after the coecients.
And seventh, the include.adjrs and include.bic arguments suppress the inclusion of the
adjustedR
2
andBIC GOF statistics. These aremodel-specic arguments, whichare denedin
the extract() methods for ‘lm’ and ‘gls’. More information about model-specic arguments
46
16
texreg: Conversion of R Model Output to L
A
T
E
Xand HTML
can be found on the help page of the generic extract() function.
5.5. An example with robust standard errors
Acommon task in econometrics is to report robust|i.e., (Eicker-)Huber-White-corrected,
or heteroskedasticity-consistent|standard errors using the sandwich (Zeileis2004,2006) and
lmtest (Zeileis and Hothorn 2002) packages. The following code shows how this can be
accomplished in combination with the texreg package. The resulting table is not reported
here.
R> library("sandwich")
R> library("lmtest")
R> hc <- vcovHC(m2)
R> ct <- coeftest(m2, vcov = hc)
R> se <- ct[, 2]
R> pval <- ct[, 4]
R> texreg(m2, override.se = se, override.pvalues = pval)
The standard errors and p values are rst extracted from the hc matrix and then handed over
to the texreg() function using the override.se and override.pvalues arguments.
5.6. htmlreg(), Microsoft Word, knitr, and Markdown
The following examples show how the htmlreg() function can be used. The output code for
these examples is not reported here.
The output of any texreg(), htmlreg() or screenreg() call can be written directly to a le
by adding the file argument. This is especially handy because HTML les can be read by
Microsoft Word if a \.doc" le extension is added.
If the table is exported to a le, it is advisable to include the full header information of
the HTML le to make sure that Microsoft Word or other programs can parse the le. An
example:
R> htmlreg(list(m1, m2, m3), file = "mytable.doc", inline.css = FALSE,
+
doctype = TRUE, html.tag = TRUE, head.tag = TRUE, body.tag = TRUE)
The doctype argument adds the document type declaration to the rst line of the HTML
document. The inline.css = FALSE argument causes the function to write cascading style
sheets (the table formatting code) into the <head> tag rather than into the table code. The
head.tag argument actually adds sucha <head> tagto the document. Similarly,the body.tag
argument wraps the table in a <body> tag, and the html.tag argument encloses both|the
<head> and the <body> tag|in an <html> tag. In other words, these arguments create a
whole HTML document rather than merely the table code. The resulting le can be read by
Microsoft Word because the HTML le has a\.doc"extension.
The htmlreg() function also works wellwith the knitr package for dynamic report generation
(Xie2013c). The default arguments are compatible with knitr and HTML. In addition to
HTML, knitr is also compatible with Markdown, a simplied markup language. texreg can
work with Markdown as well, but an additionalargument should be provided to make it work:
45
Philip Leifeld
17
R> htmlreg(list(m1, m2, m3), star.symbol = "\\*", center = TRUE,
+
doctype = FALSE)
The star.symbol = "\\*" argument makes sure that Markdown does not interpret the sig-
nicance stars as special Markdown syntax. The additional (and optional) center = TRUE
argument centers the table horizontally on the page.
5.7. Condence intervals instead of standard errors
Most model types implemented in texreg report standard errors and p values. However, some
model types report condence intervals by default. The xergm package (Leifeld,Cranmer,
and Desmarais 2014)andthelme4package(Bates et al. 2013)aretwoexamples.Ifcondence
intervals are preferred to standard errors but they are not available by default, the ci.force
argument allows conversion of standard errors to condence intervals. The ci.force.level
argument determines at which condence level the interval should be computed.
Astar is added to estimates where the condence interval does not contain the value given by
ci.test (to remove signicance stars, ci.test = NULL can be set). When the bold argument
is used in conjunction with condence intervals, bold values greater than 0 cause texreg to
print estimates in bold where the ci.test value is outside the condence interval, regardless
of the actual value of the bold argument (see Table6):
R> texreg(list(m1, m1, m2), ci.force = c(FALSE, TRUE, TRUE), ci.test = 0,
+
ci.force.level = 0.95, bold = 0.05, float.pos = "tb",
+
caption = "Enforcing confidence intervals.",
+
booktabs = TRUE, use.packages = FALSE, single.row = TRUE)
5.8. Coecient plots
Finally, it is possible to display the results of statistical models usinga coecient plot (a forest
plot applied to the estimates and condence intervals or standard errors of a regression model;
for another implementation, seeLander2013). Using the plotreg function, one or multiple
statistical modelobjects can be plotted. Most ofthe arguments of the screenreg,texreg, and
htmlreg functions are also supported by the plotreg function. Where condence intervals are
not natively available, the plotreg function converts standard errors into condence intervals.
Alternatively, the use.se argument can be used to plot error bars with one or two standard
errors from the point estimate. The diagram produced by the following code is shown in
Figure2:
R> plotreg(m1, custom.coef.names = c("Intercept", "Group Trt"))
6. Writing extensions for new models
The previous examples have demonstrated how the texreg package can be used to convert
statistical model output into plain-text, LAT
E
X, HTML, and Markdown tables. Yet, this only
works with model types known to texreg. Accordingly, this section shows how methods for
new model types can be devised and registered.
55
18
texreg: Conversion of R Model Output to L
A
T
E
Xand HTML
Model 1
Bars denote CIs.
Intercept
Group Trt
−1
0
1
2
3
4
5
l
l
Figure 2: Result of the plotreg function. Signicant estimates are colored in red.
6.1. Simple extensions
Acustom extract function can be easily implemented. For any model type, there exists a
function which extracts the relevant information from a model. For example, the extract()
methodfor ‘lm’ objects provides coecients andGOF statistics for ‘lm’objects, theextract()
method for ‘ergm’ objects provides this information for ‘ergm’ objects, etc.
To get an overview of the model type one is interested in, it is recommended to t a model and
examinethe resultingobject usingthe str(model) command, thesummary(model) command,
the summary(model)$coef command, and related approaches.
Any new extract function should retrieve the data shown in Table7 from a statistical model.
Note that pvalues and gof.decimal are optional and can be omitted. Either the se slot or
the ci.low and ci.up slots must contain values.
Once these data have been located and extracted, a ‘texreg’ object can be created and
returned to the texreg() function. The following code provides a simple example for ‘lm’
objects:
R> extract.lm <- function(model) {
+
s <- summary(model)
+
names <- rownames(s$coef)
+
co <- s$coef[, 1]
+
se <- s$coef[, 2]
+
pval <- s$coef[, 4]
+
+
rs <- s$r.squared
+
adj <- s$adj.r.squared
+
n <- nobs(model)
+
+
gof <- c(rs, adj, n)
58
Philip Leifeld
19
+
gof.names <- c("R$^2$", "Adj.\\ R$^2$", "Num.\\ obs.")
+
+
tr <- createTexreg(
+
coef.names = names,
+
coef = co,
+
se = se,
+
pvalues = pval,
+
gof.names = gof.names,
+
gof = gof
+
)
+
return(tr)
+ }
First, the names of the model terms, the coecient values, the standard errors, and the
pvalues are extracted from the modelor its summary (they can be computed if not available).
Second, various summary statistics and GOF measures are extracted from the model object
(in this case: R
2
,Adj. R
2
and Num. obs.) and saved in a numeric vector.
Third, the names of these statistics should be dened in a character vector. All vectors so
far should have the same length.
Fourth, a new ‘texreg’ object should be created, with the information extracted before in-
cluded as arguments.
Fifth, the ‘texreg’ object must be returned. This is necessary for the texreg() function to
continue processing the model.
After writing a custom function, the function has to be registered as a method for the generic
extract() function. In the above example, this can be achieved with the following code:
R> setMethod("extract", signature = className("lm", "stats"),
+
definition = extract.lm)
Assume, for instance, that an extension for ‘clogit’ objects called extract.clogit() is
written. The clogit() function (and the corresponding class denition) can be found in
the survival package (TherneauandGrambsch2000;Therneau2012). Then the code above
should be changed as follows:
R> setMethod("extract", signature = className("clogit", "survival"),
+
definition = extract.clogit)
After executingthe denition of the functionandthe adjusted setMethod() command, texreg
can be used with ‘clogit’ models.
6.2. A complete example
The following code shows the complete extract.lm() function as included in the texreg
package.
R> extract.lm <- function(model, include.rsquared = TRUE,
+
include.adjrs = TRUE, include.nobs = TRUE, ...) {
89
20
texreg: Conversion of R Model Output to L
A
T
E
Xand HTML
+
+
s <- summary(model, ...)
+
names <- rownames(s$coef)
+
co <- s$coef[, 1]
+
se <- s$coef[, 2]
+
pval <- s$coef[, 4]
+
+
gof <- numeric()
+
gof.names <- character()
+
gof.decimal <- logical()
+
if (include.rsquared == TRUE) {
+
rs <- s$r.squared
+
gof <- c(gof, rs)
+
gof.names <- c(gof.names, "R$^2$")
+
gof.decimal <- c(gof.decimal, TRUE)
+
}
+
if (include.adjrs == TRUE) {
+
adj <- s$adj.r.squared
+
gof <- c(gof, adj)
+
gof.names <- c(gof.names, "Adj.\\ R$^2$")
+
gof.decimal <- c(gof.decimal, TRUE)
+
}
+
if (include.nobs == TRUE) {
+
n <- nobs(model)
+
gof <- c(gof, n)
+
gof.names <- c(gof.names, "Num.\\ obs.")
+
gof.decimal <- c(gof.decimal, FALSE)
+
}
+
+
tr <- createTexreg(
+
coef.names = names,
+
coef = co,
+
se = se,
+
pvalues = pval,
+
gof.names = gof.names,
+
gof = gof,
+
gof.decimal = gof.decimal
+
)
+
return(tr)
+ }
R> setMethod("extract", signature = className("lm", "stats"),
+
definition = extract.lm)
In addition to the simple example code shown above, this function has several arguments,
which can be used to include or exclude various GOF or summary statistics. Additional argu-
ments can also be used in other contexts. For example, the user can decide whether random
eect variances should be included in texreg tables of ‘mer’ objects (from the lme4 package,
Documents you may be interested
Documents you may be interested