This function will output a summary statistics variable table either to the console or as an HTML file that can be viewed continuously while working with data, or sent to file for use elsewhere. st()
is the same thing but requires fewer key presses to type.
sumtable(
data,
vars = NA,
out = NA,
file = NA,
summ = NA,
summ.names = NA,
group = NA,
group.long = FALSE,
group.test = FALSE,
col.breaks = NA,
digits = NA,
fixed.digits = FALSE,
factor.percent = TRUE,
factor.counts = TRUE,
factor.numeric = FALSE,
logical.numeric = FALSE,
logical.labels = c("No", "Yes"),
labels = NA,
title = "Summary Statistics",
note = NA,
anchor = NA,
col.width = NA,
col.align = NA,
align = NA,
note.align = "l",
fit.page = "\\textwidth",
simple.kable = FALSE,
opts = list()
)st(
data,
vars = NA,
out = NA,
file = NA,
summ = NA,
summ.names = NA,
group = NA,
group.long = FALSE,
group.test = FALSE,
col.breaks = NA,
digits = NA,
fixed.digits = FALSE,
factor.percent = TRUE,
factor.counts = TRUE,
factor.numeric = FALSE,
logical.numeric = FALSE,
logical.labels = c("No", "Yes"),
labels = NA,
title = "Summary Statistics",
note = NA,
anchor = NA,
col.width = NA,
col.align = NA,
align = NA,
note.align = "l",
fit.page = "\\textwidth",
simple.kable = FALSE,
opts = list()
)
Data set; accepts any format with column names.
Character vector of column names to include, in the order you'd like them included. Defaults to all numeric, factor, and logical variables, plus any character variables with six or fewer unique values. You can include strings that aren't columns in the data (including blanks) - these will create rows that are blank except for the string (left-aligned), for spacers or subtitles.
Determines where the completed table is sent. Set to "browser"
to open HTML file in browser using browseURL()
, "viewer"
to open in RStudio viewer using viewer()
, if available. Use "htmlreturn"
to return the HTML code to R, "latex"
to return LaTeX code to R (use "latexdoc"
to get a full buildable document rather than a fragment), "return"
to return the completed summary table to R in data frame form, or "kable"
to return it in knitr::kable()
form. Combine out = "csv"
with file
to write to CSV (dropping most formatting). Defaults to "viewer"
if RStudio is running, "browser"
if it isn't, or "kable"
if it's an RMarkdown document being built with knitr
.
Saves the completed summary table file to file with this filepath. May be combined with any value of out
, although note that out = "return"
and out = "kable"
will still save the standard sumtable HTML file as with out = "viewer"
or out = "browser"
.
Character vector of summary statistics to include for numeric and logical variables, in the form 'function(x)'
. Defaults to c('notNA(x)','mean(x)','sd(x)','min(x)','pctile(x)[25]','pctile(x)[75]','max(x)')
if there's one column, or c('notNA(x)','mean(x)','sd(x)')
if there's more than one. If all variables in a column are factors it defaults to c('sum(x)','mean(x)')
for the factor dummies. If the table has multiple variable-columns and you want different statistics in each, include a list of character vectors instead. This option is flexible, and allows any summary statistic function that takes in a column and returns a single number. For example, summ=c('mean(x)','mean(log(x))')
will provide the mean of each variable as well as the mean of the log of each variable. Keep in mind the special vtable package helper functions designed specifically for this option propNA
, countNA
, and notNA
, which report counts and proportions of NAs, or counts of not-NAs, in the vectors, nuniq
, which reports the number of unique values, and pctile
, which returns a vector of the 100 percentiles of the variable. NAs will be omitted from all calculations other than propNA(x)
and countNA(x)
.
Character vector of names for the summary statistics included. If summ
is at default, defaults to c('N','Mean','Std. Dev.','Min','Pctl. 25','Pctl. 75','Max')
(or the appropriate shortened version with multiple columns) unless all variables in the column are factors in which case it defaults to c('N','Percent')
. If summ
has been set but summ.names
has not, defaults to summ
with the (x)
s removed and the first letter capitalized. If the table has multiple variable-columns and you want different statistics in each, include a list of character vectors instead.
Character variable with the name of a column in the data set that statistics are to be calculated over. Value labels will be used if found for numeric variables. Changes the default summ
to c('mean(x)','sd(x)')
.
By default, if group
is specified, each group will get its own set of columns. Set group.long = TRUE
to instead basically just make a regular sumtable()
for each group and stack them on top of each other. Good for when you have lots of groups. You can also set it to 'l'
, 'c'
, or 'r'
to determine how the group names are aligned. Defaults to centered.
Set to TRUE
to perform tests of whether each variable in the table varies over values of group
. Only works with group.long = FALSE
. Performs a joint F-test (using anova(lm))
) for numeric variables, and a Chi-square test of independence (chisq.test
) for categorical variables. If you want to adjust things like which tests are used, significance star levels, etc., see the help file for independence.test
and pass in a named list of options for that function.
Numeric vector indicating the variables (or number of elements of vars
) after which to start a new column. So for example with a data set with six variables, c(3,5)
would put the first three variables in the first column, the next two in the middle, and the last on the right. Cannot be combined with group
unless group.long = TRUE
.
Number of digits after the decimal place to report. Set to a single number for consistent digits, or a vector the same length as summ
for different digits for each calculation, or a list of vectors that match up to a multi-column summ
. Defaults to 0 for the first calculation and 2 afterwards.
FALSE
will cut off trailing 0
s when rounding. TRUE
retains them. Defaults to FALSE
.
Set to TRUE
to show factor means as percentages instead of proportions, i.e. 50%
with a column header of "Percent" rather than .5
with a column header of "Mean". Defaults to TRUE
.
Set to TRUE
to show a count of each factor level in the first column. Defaults to TRUE
.
By default, factor variable dummies basically ignore the summ
argument and show count (or nothing) in the first column and percent or proportion in the second. Set this to TRUE
to instead treat the dummies like numeric binary variables with values 0 and 1.
By default, logical variables are treated as factors with TRUE = "Yes"
and FALSE = "No"
. Set this to FALSE
to instead treat them as numeric variables rather than factors, with TRUE = 1
and FALSE = 0
.
When turning logicals into factors, use these labels for FALSE
and TRUE
, respectively, rather than "No" and "Yes".
Variable labels. labels will accept four formats: (1) A vector of the same length as the number of variables in the data that will be included in the table (tricky to use if many are being dropped, also won't work for your group
variable), in the same order as the variables in the data set, (2) A matrix or data frame with two columns and more than one row, where the first column contains variable names (in any order) and the second contains labels, (3) A matrix or data frame where the column names (in any order) contain variable names and the first row contains labels, or (4) TRUE to look in the data for variable labels set by the haven package, set_label()
from sjlabelled, or label()
from Hmisc.
Character variable with the title of the table.
Table note to go after the last row of the table. Will follow significance star note if group.test = TRUE
.
Character variable to be used to set an anchor link in HTML tables, or a label tag in LaTeX.
Vector of page-width percentages, on 0-100 scale, overriding default column widths in an HTML table. Must have a number of elements equal to the number of columns in the resulting table.
For HTML output, a character vector indicating the HTML text-align
attributes to be used in the table (for example col.align = c('left','center','center')
. Defaults to variable-name columns left-aligned and all others right-aligned (with a little extra padding between columns with col.breaks
). If you want to get tricky, you can add a ";"
afterwards and keep putting in whatever CSS attributes you want. They will be applied to the whole column.
For LaTeX output, string indicating the alignment of each column. Use standard LaTeX syntax (i.e. l|ccc
). Defaults to left in the first column and right-aligned afterwards, with @{\hskip .2in}
spacers if you have col.breaks
. If col.width
is specified, defaults to all p{}
columns with widths set by col.width
. If you want the columns aligned on a decimal point, see [this explainer](https://tex.stackexchange.com/questions/2746/aligning-numbers-by-decimal-points-in-table-columns#2747) of how to use the siunitx
package and S
-type columns.
Set the alignment for the multi-column table note. Usually "l", but if you have a long note in LaTeX you might want to set it with "p"
For LaTeX output, uses a resizebox to force the table to a certain width. Set to NA
to omit.
For out = 'kable'
, if you want the kable
printed to console rather than HTML or PDF, then the multi-column headers and table notes won't work. Set simple.kable = TRUE
to skip both.
The same sumtable
options as above, but in a named list format. Useful for applying the same set of options to multiple sumtable
s.
There are many, many functions in R that will produce a summary statisics table for you. So why use sumtable()
? sumtable()
serves two main purposes:
(1) In the same spirit as vtable()
, it makes it easy to view the summary statistics *as you work*, either in the Viewer pane or in a browser window.
(2) sumtable()
is designed to *have nice defaults* and is not really intended for deep customization. It's got lots of options, sure, but they're only intended to go so far. So you can have a summary statistics table without much work.
Keeping with point (2), sumtable()
is designed for use by people who want the kind of table that sumtable()
produces, which is itself heavily influenced by the kinds of summary statistics tables you often see in economics papers. In that regard it is most similar to stargazer::stargazer()
except that it can handle tibbles, factor variables, grouping, and produce multicolumn tables, or summarytools::dfSummary()
or skimr::skim()
except that it is easier to export with nice formatting. If you want a lot of control over your summary statistics table, check out the packages gtsummary, arsenal, qwraps2, or Amisc, and about a million more.
If you would like to include a sumtable
in an RMarkdown document, then use out="latex"
if outputting to LaTeX. If outputting to another format, use out="kable"
, perhaps followed by kableExtra::kable_styling()
for styling control. Alternately, in HTML, you can use the file
option to write to file and use a <iframe>
to include it.
# NOT RUN {
# Examples are only run interactively because they open HTML pages in Viewer or a browser.
if (interactive()) {
data(iris)
# Sumtable handles both numeric and factor variables
st(iris)
# Output to LaTeX as well for easy integration
# with RMarkdown, or \input{} into your LaTeX docs
# (specify file too to save the result)
st(iris, out = 'latex')
# Summary statistics by group
iris$SL.above.median <- iris$Sepal.Length > median(iris$Sepal.Length)
st(iris, group = 'SL.above.median')
# Add a group test, or report by-group in "long" format
st(iris, group = 'SL.above.median', group.test = TRUE)
st(iris, group = 'SL.above.median', group.long = TRUE)
# Going all out! Adding variable labels with labels,
# spacers and variable "category" titles with vars,
# Changing the presentation of the factor variable,
# and putting the factor in its own column with col.breaks
var.labs <- data.frame(var = c('SL.above.median','Sepal.Length',
'Sepal.Width','Petal.Length',
'Petal.Width'),
labels = c('Above-median Sepal Length','Sepal Length',
'Sepal Width','Petal Length',
'Petal Width'))
st(iris,
labels = var.labs,
vars = c('Sepal Variables','SL.above.median','Sepal.Length','Sepal.Width',
'Petal Variables','Petal.Length','Petal.Width',
'Species'),
factor.percent = FALSE,
col.breaks = 7)
}
# }
Run the code above in your browser using DataLab