texreg function - RDocumentation (2023)

Description

Conversion of R regression output to a LaTeX table.

Usage

texreg( l, file = NULL, single.row = FALSE, stars = c(0.001, 0.01, 0.05), custom.header = NULL, custom.model.names = NULL, custom.coef.names = NULL, custom.coef.map = NULL, custom.gof.names = NULL, custom.gof.rows = NULL, custom.note = NULL, digits = 2, leading.zero = TRUE, symbol = "\\cdot", override.coef = 0, override.se = 0, override.pvalues = 0, override.ci.low = 0, override.ci.up = 0, omit.coef = NULL, reorder.coef = NULL, reorder.gof = NULL, ci.force = FALSE, ci.force.level = 0.95, ci.test = 0, groups = NULL, custom.columns = NULL, custom.col.pos = NULL, bold = 0, center = TRUE, caption = "Statistical models", caption.above = FALSE, label = "table:coefficients", booktabs = FALSE, dcolumn = FALSE, siunitx = FALSE, lyx = FALSE, sideways = FALSE, longtable = FALSE, threeparttable = FALSE, use.packages = TRUE, table = TRUE, tabular = TRUE, no.margin = FALSE, fontsize = NULL, scalebox = NULL, float.pos = "", ...)

Arguments

l

A statistical model or a list of statistical models. Lists ofmodels can be specified as l = list(model.1, model.2, ...).Different object types can also be mixed.

file

Using this argument, the resulting table is written to a filerather than to the R prompt. The file name can be specified as a characterstring. Writing a table to a file can be useful for working with MS Officeor LibreOffice. For example, using the htmlreg function, anHTML table can be written to a file with the extension .doc andopened with MS Word. The table can then be simply copied into any Worddocument, retaining the formatting of the table. Note that LibreOffice canimport only plain HTML; CSS decorations are not supported; the resultingtables do not retain the full formatting in LibreOffice.

single.row

By default, a model parameter takes up two lines of thetable: the standard error is listed in parentheses under the coefficient.This saves a lot of horizontal space on the page and is the default tableformat in most academic journals. If single.row = TRUE is activated,however, both coefficient and standard error are placed in a single tablecell in the same line.

stars

The significance levels to be used to draw stars. Between 0 and4 threshold values can be provided as a numeric vector. For example,stars = numeric(0) will not print any stars and will not print anynote about significance levels below the table. stars = 0.05 willattach one single star to all coefficients where the p value is below 0.05.stars = c(0.001, 0.01, 0.05, 0.1) will print one, two, or threestars, or a symbol as specified by the symbol argument depending onthe p-values.

custom.header

An optional named list of multi-column headers that areplaced above the model names. For example,custom.header = list("abc" = 1:3, "ef" = 4:5) will add the label"abc" to the first three models and "ef" to the fourth andfifth model. The column with coefficient names and any custom columns addedby the "custom.columns" argument are not counted towards thesepositions. If booktabs = TRUE, \cmidrule rules are addedbelow the respective labels; otherwise \cline lines are used.

custom.model.names

A character vector of labels for the models. Bydefault, the models are named "Model 1", "Model 2", etc. Specifyingmodel.names = c("My name 1", "My name 2") etc. overrides the defaultbehavior.

custom.coef.names

By default, texreg uses the coefficient names which are stored in the models. The custom.coef.names argument can be used to replace them by other character strings in the order of appearance. For example, if a table shows a total of three different coefficients (including the intercept), the argument custom.coef.names = c("Intercept", "variable 1", "variable 2") will replace their names in this order.

Sometimes it happens that the same variable has a different name in different models. In this case, the user can use this function to assign identical names. If possible, the rows will then be merged into a single row unless both rows contain values in the same column.

Where the argument contains an NA value, the original name of the coefficient is kept. For example, custom.coef.names = c(NA, "age", NA) will only replace the second coefficient name and leave the first and third name as they are in the original model.

See also custom.coef.map for an easier and more comprehensive way to rename, omit, and reorder coefficients.

custom.coef.map

The custom.coef.map argument can be used to select, omit, rename, and reorder coefficients.

Users must supply a named list of this form: list("x" = "First variable", "y" = NA, "z" = "Third variable"). With that particular example of custom.coef.map,

  1. coefficients will be presented in order: "x", "y", "z".

  2. variable "x" will appear as "First variable", variable "y" will appear as "y", and variable "z" will appear as "Third variable".

  3. all variables not named "x", "y", or "z" will be omitted from the table.

custom.gof.names

(Video) Adding documentation to your R function with roxygen2

A character vector which is used to replace thenames of the goodness-of-fit statistics at the bottom of the table. Thevector must have the same length as the number of GOF statistics in thefinal table. The argument works like the custom.coef.names argument,but for the GOF values. NA values can be included where the originalGOF name should be kept.

custom.gof.rows

A named list of vectors for new lines at thebeginning of the GOF block of the table. For example, list("Randomeffects" = c("YES", "YES", "NO"), Observations = c(25, 25, 26)) wouldinsert two new rows into the table, at the beginning of the GOF block(i.e., after the coefficients). The rows can contain integer, numeric, orcharacter objects. Note that this argument is processed after thecustom.gof.names argument (meaning custom.gof.names shouldnot include any of the new GOF rows) and before the reorder.gofargument (meaning that the new GOF order specified there should containvalues for the new custom GOF rows). Arguments for custom columns are notaffected because they only insert columns into the coefficient block.

custom.note

With this argument, a replacement text for the significance note below the table can be provided. If an empty character object is provided (custom.note = ""), the note will be omitted completely. If some character string is provided (e.g., custom.note = "My note"), the significance legend is replaced by My note. The original significance legend can be included by inserting the %stars wildcard. For example, a custom note can be added right after the significance legend by providing custom.note = "%stars. My note.".

If the threeparttable argument is used, any note should be preceded by "\\item", for example "\\item %stars. \\item Second note. \\item Third note.", and it is possible to create line breaks in the formatted table by including "\\\\" and line breaks in the LaTeX code by including "\n", for example "\n\\item %stars.\\\\\n\\item Second line.\n".

digits

Set the number of decimal places for coefficients, standarderrors and goodness-of-fit statistics. Do not use negative values! Theargument works like the digits argument in theround function of the base package.

leading.zero

Most journals require leading zeros of coefficients andstandard errors (for example, 0.35). This is also the default texregbehavior. Some journals, however, require omission of leading zeros (forexample, .35). This can be achieved by setting leading.zero =FALSE.

symbol

If four threshold values are handed over to the starsargument, p-values smaller than the largest threshold value but larger thanthe second-largest threshold value are denoted by this symbol. The defaultsymbol is "\\cdot" for the LaTeX dot, "·" for theHTML dot, or simply "." for the ASCII dot. If thetexreg function is used, any other mathematical LaTeX symbolor plain text symbol can be used, for example symbol = "\\circ"for a small circle (note that backslashes must be escaped). If thehtmlreg function is used, any other HTML character or symbolcan be used. For the screenreg function, only plain text characterscan be used.

override.coef

Set custom values for the coefficients. New coefficientsare provided as a list of numeric vectors. The list contains vectors ofcoefficients for each model. There must be as many vectors of coefficientsas there are models. For example, if there are two models with three modelterms each, the argument could be specified as override.coef =list(c(0.1, 0.2, 0.3), c(0.05, 0.06, 0.07)). If there is only one model,custom values can be provided as a plain vector (not embedded in a list).For example: override.coef = c(0.05, 0.06, 0.07).

override.se

Set custom values for the standard errors. New standarderrors are provided as a list of numeric vectors. The list contains vectorsof standard errors for each model. There must be as many vectors ofstandard errors as there are models. For example, if there are two modelswith three coefficients each, the argument could be specified asoverride.se = list(c(0.1, 0.2, 0.3), c(0.05, 0.06, 0.07)). If thereis only one model, custom values can be provided as a plain vector (notembedded in a list).For example: override.se = c(0.05, 0.06, 0.07).Overriding standard errors can be useful for the implementation of robustSEs, for example.

override.pvalues

Set custom values for the p-values. New p-values areprovided as a list of numeric vectors. The list contains vectors ofp-values for each model. There must be as many vectors of p-values as thereare models. For example, if there are two models with three coefficientseach, the argument could be specified as override.pvalues =list(c(0.1, 0.2, 0.3), c(0.05, 0.06, 0.07)). If there is only one model,custom values can be provided as a plain vector (not embedded in a list).For example: override.pvalues = c(0.05, 0.06, 0.07). Overridingp-values can be useful for the implementation of robust SEs and p-values,for example.

override.ci.low

Set custom lower confidence interval bounds. Thisworks like the other override arguments, with one exception: if confidenceintervals are provided here and in the override.ci.up argument, thestandard errors and p-values as well as the ci.force argument areignored.

override.ci.up

Set custom upper confidence interval bounds. Thisworks like the other override arguments, with one exception: if confidenceintervals are provided here and in the override.ci.low argument, thestandard errors and p values as well as the ci.force argument areignored.

(Video) R Functions and R Documentation

omit.coef

A character string which is used as a regular expression toremove coefficient rows from the table. For example, omit.coef ="group" deletes all coefficient rows from the table where the name of thecoefficient contains the character sequence "group". More complexregular expressions can be used to filter out several kinds of model terms,for example omit.coef = "(thresh)|(ranef)" to remove all model termsmatching either "thresh" or "ranef". The omit.coefargument is processed after the custom.coef.names argument, so theregular expression should refer to the custom coefficient names. To omitGOF entries instead of coefficient entries, use the custom arguments of theextract functions instead (see the help entry of the extractfunction.

reorder.coef

Reorder the rows of the coefficient block of theresulting table in a custom way. The argument takes a vector of the samelength as the number of coefficients. For example, if there are threecoefficients, reorder.coef = c(3, 2, 1) will put the thirdcoefficient in the first row and the first coefficient in the third row.Reordering can be sensible because interaction effects are often added tothe end of the model output although they were specified earlier in themodel formula. Note: Reordering takes place after processing customcoefficient names and after omitting coefficients, so thecustom.coef.names and omit.coef arguments should follow theoriginal order.

reorder.gof

Reorder the rows of the goodness-of-fit block of theresulting table in a custom way. The argument takes a vector of the samelength as the number of GOF statistics. For example, if there are threegoodness-of-fit rows, reorder.gof = c(3, 2, 1) will exchange thefirst and the third row. Note: Reordering takes place after processingcustom GOF names and after adding new custom GOF rows, so thecustom.gof.names and custom.gof.rows arguments should followthe original order, and the reorder.gof argument should containvalues for any rows that are added through the custom.gof.rowsargument.

ci.force

Should confidence intervals be used instead of the defaultstandard errors and p-values? Most models implemented in the texregpackage report standard errors and p-values by default while few modelsreport confidence intervals. However, the functions in the texregpackage can convert standard errors and into confidence intervals usingz-scores if desired. To enforce confidence intervals instead of standarderrors, the ci.force argument accepts either a logical valueindicating whether all models or none of the models should be forced toreport confidence intervals (ci.force = TRUE for all andci.force = FALSE for none) or a vector of logical values indicatingfor each model separately whether the model should be forced to reportconfidence intervals (e.g., ci.force = c(FALSE, TRUE, FALSE)).Confidence intervals are computed using the standard normal distribution(z-values based on the qnorm function). Thet-distribution is currently not supported because this would require eachextract method to have an additional argument for the degreesof freedom.

ci.force.level

If the ci.force argument is used to convertstandard errors to confidence intervals, what confidence level should beused? By default, 0.95 is used (i.e., an alpha value of 0.05).

ci.test

If confidence intervals are reported, the ci.testargument specifies the reference value to establish whether acoefficient/CI is significant. The default value ci.test = 0, forexample, will attach a significance star to coefficients if the confidenceinterval does not contain 0. A value of ci.test = 1 could beuseful if coefficients are provided on the odds-ratio scale, for example.If no star should be printed at all, ci.test = NA can be used. It ispossible to provide a single value for all models or a vector with aseparate value for each model. The ci.test argument works both formodels with native support for confidence intervals and in cases where theci.force argument is used.

groups

This argument can be used to group the rows of the table intoblocks. For example, there could be one block for hypotheses and anotherblock for control variables. Each group has a heading, and the row labelswithin a group are indented. The partitions must be handed over as a listof named numeric vectors, where each number is a row index and each name isthe heading of the group. Example: groups = list("first group" = 1:4,"second group" = 7:8).

custom.columns

An optional list of additional text columns to beinserted into the coefficient block of the table, for example coefficienttypes. The list should contain one or more character vectors with as manycharacter or numeric elements as there are coefficients/model terms. If thevectors in the list are named, the names are used as labels in the tableheader. For example,custom.columns = list(type = c("a", "b", "c"), 1:3) will add twocolumns; the first one is labeled while the second one is not. Note thatthe numeric elements of the second column will be converted tocharacter objects in this example. The consequence is that decimalalignment with the dcolumn package is switched off in these columns.Note that this argument is processed after any arguments that affect thenumber of rows.

custom.col.pos

An optional integer vector of positions for the columnsgiven in the custom.columns argument. For example, if there arethree custom columns, custom.col.pos = c(1, 3, 3) will insert thefirst custom column before the first column of the original table and theremaining two custom columns after the second column of the original table.By default, all custom columns are placed after the first column, whichusually contains the coefficient names.

bold

The p-value threshold below which the coefficient shall beformatted in a bold font. For example, bold = 0.05 will cause allcoefficients that are significant at the 95% level to be formatted inbold. Note that this is not compatible with the dcolumn orsiunitx arguments in the texreg function. If bothbold and dcolumn or siunitx are TRUE,dcolumn and siunitx are switched off, and a warning messageappears. Note also that it is advisable to use stars = FALSEtogether with the bold argument because having both boldedcoefficients and significance stars usually does not make any sense.

center

Should the table be horizontally aligned at the center of thepage?

(Video) regression models: stepwise variable selection in R step() function

caption

Set the caption of the table.

caption.above

Should the caption of the table be placed above thetable? By default, it is placed below the table.

label

Set the label of the table environment.

booktabs

Use the booktabs LaTeX package to get thick horizontalrules in the output table (recommended).

dcolumn

Use the dcolumn LaTeX package to get a nice alignment ofthe coefficients at the decimal separator (recommended for use with thetexreg function). Note that only one of the three argumentsbold, dcolumn, and siunitx can be used at a time asthey are mutually incompatible.

siunitx

Use the siunitx LaTeX package to get a nice alignment ofthe coefficients at the decimal separator (recommended for use with thetexreg function). Note that only one of the three argumentsbold, dcolumn, and siunitx can be used at a time asthey are mutually incompatible.

lyx

logical; if TRUE, each new line in the output isdoubled, which facilitates transferring the output into the LyX documentprocessor.

sideways

If sideways = TRUE is set, the table floatingenvironment is replaced by a sidewaystable float, and therotating package is loaded in the preamble. The argument only has aneffect if table = TRUE is also set.

longtable

If longtable = TRUE is set, the longtableenvironment from the longtable LaTeX package is used to set tablesacross multiple pages. Note that this argument is not compatible with thesideways and scalebox arguments. These arguments will beautomatically switched off when longtable = TRUE is set.

threeparttable

If threeparttable = TRUE is set, thethreeparttable environment will be used to enclose thetabular environment in the LaTeX code, and the significance notewill be enclosed in a tablenotes environment. This permits wordwrapping of long table notes and adequate spacing between multiple notes.See also the custom.note argument. If longtable is used,the threeparttablex LaTeX package is used instead of thethreeparttable package.

(Video) R programming for beginners: using functions and objects in R

use.packages

If this argument is set to TRUE (= the defaultbehavior), the required LaTeX packages are loaded in the beginning. If setto FALSE, the use package statements are omitted from the output.

table

By default, texreg puts the actual tabular objectin a table floating environment. To get only the tabularobject without the whole table header, set table = FALSE.

tabular

By default, the table contents are wrapped in a tabularenvironment. To get only the contents for each row without the environment,set tabular = FALSE. Note that if tabular = FALSE, thetable argument must also be FALSE, otherwise a warning isprinted. Switching off the tabular environment may be useful for designingone's own table more flexibly, for example using tabular* ortabularx environments in LaTeX.

no.margin

In order to save space, inner margins of tables can beswitched off.

fontsize

The fontsize argument serves to change the font sizeused in the table. Valid values are "tiny", "scriptsize","footnotesize", "small", "normalsize", "large","Large", "LARGE", "huge", and "Huge". Note thatthe scalebox argument often achieves better results when the goal isto change the size of the table.

scalebox

The scalebox argument serves to resize the table. Forexample, scalebox = 1.0 is equivalent to the normal size,scalebox = 0.5 decreases the size of the table by one half, andscalebox = 2.0 doubles the space occupied by the table. Note thatthe scalebox argument does not work when the longtableargument is used.

float.pos

This argument specifies where the table should be located onthe page or in the document. By default, no floating position is specified,and LaTeX takes care of the position automatically. Possible values include"h" (here), "p" (page), "t" (top), "b"(bottom), any combination thereof, e.g., "tb", or any of thesevalues followed by an exclamation mark, e.g. "t!", in order toenforce this position. The square brackets do not have to be specified.

...

Custom options to be passed on to the extractfunction. For example, most extract methods provide custom options for theinclusion or exclusion of specific goodness-of-fit statistics. See the helpentries of extract for more information.

Value

A character object with a regression table and LaTeX markup. The object has an additional "texregTable" class identifier, which causes the object to be formatted nicely on screen when printed.

Details

The texreg function creates LaTeX code for inclusion in a LaTeXdocument or for usage with Sweave or knitr, based on a list ofstatistical models.

References

Leifeld, Philip (2013). texreg: Conversion of Statistical Model Output in R to LaTeX and HTML Tables. Journal of Statistical Software 55(8): 1-24. 10.18637/jss.v055.i08.

See Also

texreg-package extract

Other texreg: htmlreg(),huxtablereg(),knitreg(),matrixreg(),plotreg(),screenreg(),wordreg()

Examples

Run this code

# NOT RUN {# Linear mixed-effects modelslibrary("nlme")model.1 <- lme(distance ~ age, data = Orthodont, random = ~ 1)model.2 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1)texreg(list(model.1, model.2), booktabs = TRUE, dcolumn = TRUE)# Ordinary least squares model (example from the 'lm' help file)ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)group <- gl(2,10,20, labels = c("Ctl","Trt"))weight <- c(ctl, trt)lm.D9 <- lm(weight ~ group)table.string <- texreg(lm.D9, return.string = TRUE)cat(table.string)# }

Run the code above in your browser using DataCamp Workspace

(Video) How to Document a Function in Your R Package

Videos

1. tApply Function in R | R Tutorial 1.16 | MarinStatsLectures
(MarinStatsLectures-R Programming & Statistics)
2. How to Integrate R Code to LaTeX using RStudio (LaTeX Advanced Tutorial-13)
(Chandra Has)
3. Separate Function in R - How to Separate One Column into Two Variables
(thatRnerd)
4. Extract Fitted Values from Linear Regression Model in R (Example) | fitted() vs. predict() Functions
(Statistics Globe)
5. R Tutorial: Refresher on xts and the plot() function Arnaud Amsellem The R Trader
(DataCamp)
6. replace Function in R (Example) | How to Apply x, list & values Arguments | Exchange Value in Data
(Statistics Globe)
Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated: 05/01/2023

Views: 5780

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.