### Install and Load Summarytools Source: https://context7.com/dcomtois/summarytools/llms.txt Instructions for installing the package from CRAN or GitHub and loading it into the R environment. ```R install.packages("summarytools") # From GitHub install.packages("remotes") library(remotes) install_github("rapporter/pander") install_github("dcomtois/summarytools", build_vignettes = TRUE) # Load library(summarytools) ``` -------------------------------- ### Install summarytools from GitHub Source: https://github.com/dcomtois/summarytools/blob/master/README.md Installs the latest development version of summarytools from GitHub using the remotes package. It also installs the recommended pander dependency for improved output formatting. ```R install.packages("remotes") library(remotes) install_github("rapporter/pander") install_github("dcomtois/summarytools", build_vignettes = TRUE) ``` -------------------------------- ### Install Magick++ on Solaris Source: https://github.com/dcomtois/summarytools/blob/master/README.md Sets up the OpenCSW repository and installs the ImageMagick package on Solaris systems. ```bash pkgadd -d http://get.opencsw.org/now /opt/csw/bin/pkgutil -U /opt/csw/bin/pkgutil -y -i imagemagick /usr/sbin/pkgchk -L CSWimagemagick ``` -------------------------------- ### Install Magick++ on Debian/Ubuntu/Linux Mint Source: https://github.com/dcomtois/summarytools/blob/master/README.md Installs the Magick++ development libraries required for summarytools functionality on Debian-based systems. ```bash sudo apt install libmagick++-dev ``` -------------------------------- ### Install Magick++ on Older Ubuntu Versions Source: https://github.com/dcomtois/summarytools/blob/master/README.md Configures the OpenCPU PPA and installs Magick++ development libraries for older Ubuntu releases like Trusty or Xenial. ```bash sudo add-apt-repository -y ppa:opencpu/imagemagick sudo apt-get update sudo apt-get install -y libmagick++-dev ``` -------------------------------- ### Install Magick++ on Fedora/Red Hat/CentOS Source: https://github.com/dcomtois/summarytools/blob/master/README.md Installs the ImageMagick C++ development libraries using the yum package manager. ```bash sudo yum install ImageMagick-c++-devel ``` -------------------------------- ### Install summarytools from CRAN Source: https://github.com/dcomtois/summarytools/blob/master/README.md Installs the stable version of the summarytools package directly from the Comprehensive R Archive Network (CRAN). ```R install.packages("summarytools") ``` -------------------------------- ### Content Production Examples in R Source: https://github.com/dcomtois/summarytools/wiki/Documentation-(Developer's-Perspective) Demonstrates the core content production functions of the Summarytools package, including dfSummary, stby, and descr. These functions are used for summarizing data frames and performing by-group analysis. ```r dfs_iris1 <- dfSummary(iris) dfs_iris2 <- stby(iris, iris$Species, dfSummary) descr_iris <- iris %>% group_by(Species) %>% descr() ``` -------------------------------- ### R Markdown Integration with Summarytools Source: https://context7.com/dcomtois/summarytools/llms.txt Configures summarytools for use within R Markdown documents via the setup chunk. Demonstrates using dfSummary(), freq(), and descr() with options suitable for R Markdown output, including setting global options and using `results='asis'`. ```r # Setup chunk for R Markdown documents ```{r setup, include=FALSE} library(summarytools) st_options(plain.ascii = FALSE, style = "rmarkdown", dfSummary.varnumbers = FALSE, dfSummary.valid.col = FALSE, dfSummary.graph.magnif = 0.75, tmp.img.dir = "./img") knitr::opts_chunk$set(echo = TRUE, results = 'asis') ``` # Using dfSummary in R Markdown ```{r} dfSummary(tobacco, plain.ascii = FALSE, style = "grid", graph.magnif = 0.75, tmp.img.dir = "./img") ``` # Using freq() with results='asis' ```{r, results='asis'} freq(tobacco$gender, style = "rmarkdown") ``` # Using descr() in R Markdown ```{r, results='asis'} descr(tobacco, stats = "common", style = "rmarkdown") ``` # Alternative: use print with method = "render" ```{r} print(dfSummary(tobacco), method = "render") ``` ``` -------------------------------- ### Set Global Options with st_options() Source: https://context7.com/dcomtois/summarytools/llms.txt Explains how to use `st_options()` to query and set global options for the summarytools package, affecting default behaviors across all functions. Examples include setting rounding digits, output style, footnotes, and function-specific parameters. ```R library(summarytools) # View all current options st_options() # Query specific option st_options("round.digits") # Query multiple options st_options(c("plain.ascii", "style", "footnote")) # Set single option st_options(plain.ascii = FALSE) # Set multiple options st_options(plain.ascii = FALSE, style = "rmarkdown", footnote = NA) # Reset all options to defaults st_options("reset") # or st_options(0) # Common options for R Markdown setup st_options(plain.ascii = FALSE, style = "rmarkdown", dfSummary.graph.col = FALSE, # Disable graphs footnote = NA) # Function-specific options st_options(freq.totals = FALSE, # No totals in freq() freq.cumul = FALSE, # No cumulative in freq() descr.stats = "common", # Only common stats in descr() descr.transpose = TRUE) # Transpose descr() output # dfSummary specific options st_options(dfSummary.varnumbers = FALSE, dfSummary.valid.col = FALSE, dfSummary.graph.magnif = 0.75) # Set language (en, es, fr, pt, ru, tr) st_options(lang = "fr") # Disable X11 for headless environments st_options(use.x11 = FALSE) # Custom statistics in dfSummary st_options(dfSummary.custom.1 = expression( paste( "Q1 - Q3 :", format_number(quantile(column_data, probs = .25, type = 2, names = FALSE, na.rm = TRUE), round.digits), "-", format_number(quantile(column_data, probs = .75, type = 2, names = FALSE, na.rm = TRUE), round.digits) ) )) # Reset custom stats to default st_options(dfSummary.custom.1 = "default") ``` -------------------------------- ### R: Setup and Configuration for summarytools Source: https://github.com/dcomtois/summarytools/blob/master/doc/Custom-Statistics-in-dfSummary.html Configures the knitr package and summarytools options for generating reports. It suppresses package startup messages and sets various display preferences like disabling ASCII output, hiding headings, and controlling decimal rounding. ```r library(knitr) opts_chunk$set(comment = NA, prompt = FALSE, cache = FALSE, echo = TRUE, results = 'asis') suppressPackageStartupMessages(library(summarytools)) st_options(plain.ascii = FALSE, headings = FALSE, footnote = NA, round.digits = 1, dfSummary.graph.magnif = .85, dfSummary.varnumbers = FALSE, dfSummary.valid.col = FALSE) ``` -------------------------------- ### Manage Variable Labels with label() Source: https://context7.com/dcomtois/summarytools/llms.txt Demonstrates the usage of the `label()` function for getting and setting labels for variables and data frames. This is useful for data documentation and improving the readability of output from summarytools functions. ```R library(summarytools) data(tobacco) # Get label of a variable label(tobacco$gender) #> [1] NA # Set label for a variable label(tobacco$age) <- "Age of the participant" label(tobacco$age) #> [1] "Age of the participant" # Get data frame label label(tobacco) # Set data frame label label(tobacco) <- "Simulated tobacco study dataset" # Get all variable labels in a data frame label(tobacco, all = TRUE) # Get labels with fallback to variable names label(tobacco, all = TRUE, fallback = TRUE) # Simplified output (vector instead of list) label(tobacco, all = TRUE, fallback = TRUE, simplify = TRUE) # Clear a label label(tobacco$age) <- NA # Set labels for all columns at once label(tobacco) <- c("Gender", "Age", "Age Group", "Smoker Status", "Number of Cigarettes", "Disease Status", "Sample Weights", "BMI", NA) # Remove all labels from a data frame tobacco_unlabeled <- unlabel(tobacco) ``` -------------------------------- ### Customize Summarytools Output Source: https://github.com/dcomtois/summarytools/blob/master/doc/Custom-Statistics-in-dfSummary.html This example demonstrates how to customize the output of the dfSummary function by setting specific options. Setting 'dfSummary.custom.1' to NA removes the IQR (CV) line from the summary statistics. The output is rendered using the 'render' method. ```R st_options(dfSummary.custom.1 = NA) print(dfSummary(iri), method = "render") ``` -------------------------------- ### Convert Descriptive Statistics to Tibble Source: https://context7.com/dcomtois/summarytools/llms.txt Demonstrates how to convert descriptive statistics generated by the `descr()` function into a tibble format using `tb()`. It shows examples for common statistics and grouped results, including options for ordering and recalculating percentages. ```R library(summarytools) tb(descr(iris, stats = "common")) #> # A tibble: 4 x 6 #> variable mean sd min med max #> #> 1 Petal.Length 3.76 1.77 1 4.35 6.9 #> 2 Petal.Width 1.20 0.76 0.1 1.3 2.5 #> 3 Sepal.Length 5.84 0.83 4.3 5.8 7.9 #> 4 Sepal.Width 3.06 0.44 2 3 4.4 # Convert grouped results grouped_descr <- with(tobacco, stby(BMI, gender, descr, stats = "fivenum")) tb(grouped_descr) # Order by analysis variable tb(grouped_descr, order = 2) # Place analysis variable first tb(grouped_descr, order = 3) # Recalculate percentages for grouped freq (sums to 100%) grouped_freq <- with(tobacco, stby(smoker, gender, freq)) tb(grouped_freq, recalculate = TRUE) # Drop variable column for single-variable descr tb(descr(tobacco$BMI), drop.var.col = TRUE) ``` -------------------------------- ### Configure Global Options and Language Source: https://github.com/dcomtois/summarytools/blob/master/NEWS.md Demonstrates how to set global options for the summarytools package, including changing the output language to French or Spanish and setting multiple configuration parameters simultaneously. ```R library(summarytools) # Set output language to French st_options(lang='fr') # Set multiple options at once st_options(headings = FALSE, style = 'rmarkdown', plain.ascii = FALSE) ``` -------------------------------- ### Configure Summarytools Options (R) Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Sets global options for summarytools, including plain ASCII output and the default style for R Markdown documents. This is useful for ensuring consistent output across multiple function calls. ```r st_options(plain.ascii = FALSE, style = "rmarkdown") ``` -------------------------------- ### Initialize knitr and summarytools Global Settings Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Configures knitr chunk options and summarytools global settings to optimize output for R Markdown vignettes, including hiding redundant messages and setting the CSS style. ```R library(knitr) opts_chunk$set(comment=NA, prompt=FALSE, cache=FALSE, echo=TRUE, results='asis') st_options(bootstrap.css = FALSE, plain.ascii = FALSE, style = "rmarkdown", dfSummary.silent = TRUE, footnote = NA, subtitle.emphasis = FALSE) ``` -------------------------------- ### Generate Grid-Style Summary with dfSummary Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Creates a grid-formatted summary table for a dataset. It requires setting plain.ascii to FALSE and specifying a temporary image directory for graph rendering. ```R dfSummary(tobacco, plain.ascii = FALSE, style = 'grid', graph.magnif = 0.85, varnumbers = FALSE, valid.col = FALSE, tmp.img.dir = "/tmp") ``` -------------------------------- ### JavaScript Text Content Extraction Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html This function extracts text content from various DOM node types. It handles element nodes, text nodes, and document fragments, concatenating text from child nodes recursively. It's a utility for getting plain text from HTML structures. ```javascript function o(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else while(t=e[r++])n+=o(t);return n} ``` -------------------------------- ### Initializing Tabsets and MathJax Source: https://github.com/dcomtois/summarytools/blob/master/doc/Custom-Statistics-in-dfSummary.html This JavaScript code initializes tabsets for the document and loads the MathJax library for rendering mathematical formulas. It ensures that interactive elements and mathematical content are correctly displayed. ```javascript $(document).ready(function () { window.buildTabsets("TOC"); }); $(document).ready(function () { $('.tabset-dropdown > .nav-tabs > li').click(function () { $(this).parent().toggleClass('nav-tabs-open'); }); }); (function () { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"; document.getElementsByTagName("head")[0].appendChild(script); })(); ``` -------------------------------- ### Render HTML Summary with dfSummary Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Generates an HTML-rendered summary table. This method is preferred for R Markdown as it handles image directory management automatically. ```R print(dfSummary(tobacco, varnumbers = FALSE, valid.col = FALSE, graph.magnif = 0.82), method = 'render') ``` -------------------------------- ### Access summarytools Package News Source: https://github.com/dcomtois/summarytools/blob/master/README.md Displays the news file for the summarytools package to review recent changes and version history. ```R news(package="summarytools") ``` -------------------------------- ### Configure summarytools for R Markdown Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Sets global options for the summarytools package to ensure compatibility with R Markdown output formats, such as disabling plain ASCII and setting the style to rmarkdown. ```R library(summarytools) st_options( plain.ascii = FALSE, style = "rmarkdown", dfSummary.style = "grid", dfSummary.valid.col = FALSE, dfSummary.graph.magnif = .52, subtitle.emphasis = FALSE, tmp.img.dir = "/tmp" ) ``` -------------------------------- ### Display Results in Viewer/Browser using view() Source: https://context7.com/dcomtois/summarytools/llms.txt Illustrates how to use the `view()` function to display summarytools results in the RStudio Viewer, a web browser, or save them as HTML or Markdown files. It covers various customization options like file output, report titles, footnotes, and collapsible sections. ```R library(summarytools) data(tobacco) # View in RStudio Viewer (default) view(dfSummary(tobacco)) # View in web browser view(dfSummary(tobacco), method = "browser") # Save to HTML file view(dfSummary(tobacco), file = "tobacco_summary.html") # Save to Markdown file view(freq(tobacco$gender), file = "gender_freq.md", method = "pander") # Custom report title view(dfSummary(tobacco), file = "report.html", report.title = "Tobacco Dataset Summary") # For R Markdown with method = "render" # In an R Markdown code chunk: # ```{r, results='asis'} # view(dfSummary(tobacco), method = "render") # ``` # Grouped results grouped_results <- with(tobacco, stby(smoker, gender, freq)) view(grouped_results) # With custom footnote view(dfSummary(tobacco), footnote = "Generated with summarytools") # Disable footnote view(dfSummary(tobacco), footnote = NA) # Collapsible sections (for large outputs) view(dfSummary(tobacco), collapse = 1) ``` -------------------------------- ### Generate Data Summaries with summarytools Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html This snippet demonstrates how to use the summarytools package to generate descriptive statistics for a dataframe. It covers the basic usage of the freq and descr functions. ```R library(summarytools) data(iris) freq(iris$Species) descr(iris) ``` -------------------------------- ### Descriptive Statistics with Render Method and Small Table Class (R) Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Generates descriptive statistics and applies a small table class to reduce the width of the output table. This is useful for fitting wider tables into constrained R Markdown layouts when using the 'render' method. ```r print(descr(tobacco), method = 'render', table.classes = 'st-small') ``` -------------------------------- ### Bootstrap Tooltip Plugin Constructor Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Defines the constructor for the Bootstrap tooltip plugin. It sets up default options and extends the functionality of the base tooltip class. This is crucial for creating new tooltip instances. ```javascript var c=function(a,b){this.init("tooltip",a,b)};c.VERSION="3.3.5",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{animation:!0,template:'',trigger:"hover focus",title:"",delay:0,html:!1,placement:"top",offset:0,fallbackPlacement:"flip",container:!1,boundary:!1}),c.prototype.init=function(b,c,d){a(c).attr("data-toggle","tooltip"),c.options=a.extend({},this.getDefaults(),d,{template:this.getDefaults().template}),this.enabled=this.টারিEnabled(),this.$element=$(c),this.type=b,this.options=c.options.template,this.enabled=this.options.enabled,this.$tip=null,this.bounds={}},c.prototype.enter=function(b){var c=b||this,d=a(b.currentTarget).data("bs.tooltip");d||(d=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs.tooltip",d));var e=a(b.currentTarget).data("animation");return d.options.animation=void 0!==e?e:d.options.animation,b?(d.inState.click=!1,d.inState.focus=!0,d.inState.hover=!0,d.enter(d)):a(b.currentTarget).one("mouseenter",a.proxy(d.enter,d)),d.tip().hasClass("in")||d.hoverState==c.hoverState?void this.leave(d): (d.hoverState=c.hoverState=b?"in":"out",d.options.delay&&d.options.delay.show? (d.timeout=setTimeout(function(){"in"==c.hoverState&&c.enterContent(b)},d.options.delay.show)):c.enterContent(b),void d.$element.trigger(d.hoverState==c.hoverState?"shown.bs.tooltip":""))} ``` -------------------------------- ### Apply Global Box Sizing and Typography Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Sets the global box-sizing model to border-box for all elements and configures default font families and line heights for the document body. ```css *{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff} ``` -------------------------------- ### Initialize Bootstrap Tooltip Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Initializes tooltips on elements. Tooltips are often used to provide additional context or information when a user hovers over an element. This function handles the creation and management of tooltip instances. ```javascript function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide|show|toggle/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})} ``` -------------------------------- ### Controlling Print Output of Summarytools Objects Source: https://context7.com/dcomtois/summarytools/llms.txt Demonstrates various methods and options to control the output format of summarytools objects, such as frequency tables and data frame summaries. Options include rendering to HTML, opening in a browser, saving to files, and customizing headings, titles, footnotes, table height, and CSS classes. ```r library(summarytools) data(tobacco) # Default console output print(freq(tobacco$gender)) # Render HTML in R Markdown print(freq(tobacco$gender), method = "render") # Open in browser print(freq(tobacco$gender), method = "browser") # Save to file print(freq(tobacco$gender), file = "gender_freq.html") print(freq(tobacco$gender), file = "gender_freq.md", method = "pander") # Without headings print(freq(tobacco$gender), headings = FALSE) # Custom report title (HTML only) print(dfSummary(tobacco), file = "report.html", report.title = "Data Summary Report") # Add custom footnote print(dfSummary(tobacco), method = "browser", footnote = "Note: This is a simulated dataset") # Maximum table height with scroll (HTML) print(dfSummary(tobacco), method = "browser", max.tbl.height = 500) # Table CSS classes print(dfSummary(tobacco), method = "browser", table.classes = "table-striped table-bordered") # Exclude Bootstrap CSS (for Shiny apps) print(dfSummary(tobacco), method = "render", bootstrap.css = FALSE) ``` -------------------------------- ### Initialize Bootstrap Popover Component Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Extends jQuery with a popover plugin that manages content rendering and visibility. It handles HTML content injection and provides a noConflict method for library compatibility. ```javascript c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()}; ``` -------------------------------- ### Manage Tab Switching Logic Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Handles tab activation and content switching. It triggers hide/show events and manages CSS transitions for smooth tab navigation. ```javascript c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}}; ``` -------------------------------- ### Format summarytools objects with kableExtra in R Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Demonstrates converting summarytools objects (from descr and stby) into tibbles for formatting with the kableExtra package. This allows for advanced table customization in R, such as collapsing rows and specifying HTML output. Requires the kableExtra and magrittr packages. ```R library(kableExtra) library(magrittr) stby(iris, iris$Species, descr, stats = "fivenum") |> tb() |> kable(format = "html", digits = 2) |> collapse_rows(columns = 1, valign = "top") ``` ```R stby(iris, iris$Species, descr, stats = "fivenum") |> tb(order = 3) |> kable(format = "html", digits = 2) |> collapse_rows(columns = 1, valign = "top") ``` -------------------------------- ### Bootstrap Modal Initialization and Events (jQuery) Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html This snippet demonstrates how to initialize Bootstrap modals using jQuery. It covers handling modal show and hidden events, ensuring proper focus management after the modal is closed. It's designed for use with the Bootstrap framework and jQuery. ```javascript +function(a){'use strict';var d=a('[data-toggle="modal"]'),e=a('[data-dismiss="modal"]'),f=a('.modal-backdrop, .modal-backdrop-y'),g=/(transition|in)/,h=function(b){return this.each(function(){var c=a(this),d=c.data('bs.modal'),e=a.extend({remote:!/#/.test(c.attr('href'))&&c.attr('href')},c.data(),a(this).data());d||c.data('bs.modal',(d=new k(this,e)));'toggle'==b&&d[b]()})});d.length?d.data('bs.modal')||d.one('click.bs.modal',function(b){a(this).one('click.dismiss.bs.modal',function(a){a.preventDefault();d.show()});var c=a(this),e=c.attr('href');f=a(e);if(!f.length)f=a('[data-target="#'+e.replace(/.*\[#\](?=.*$)/,"")+'"]');f.length&&f.data('bs.modal')||f.modal({backdrop:!1});h.call(c,a.extend({remote:!/#/.test(c.attr('href'))&&c.attr('href')},f.data(),c.data())).one('show.bs.modal',function(a){a.isDefaultPrevented()||f.one('hidden.bs.modal',function(){d.is(':visible')&&d.trigger('focus')})})})}:a.fn.modal=h,a.fn.modal.Constructor=k,a.fn.modal.noConflict=function(){return a.fn.modal=i,this},a(document).on('click.bs.modal.data-api','[data-toggle="modal"]',function(b){var c=a(this),d=c.attr('href');var e=a(d);if(!e.length)e=a('[data-target="#'+d.replace(/.*\[#\](?=.*$)/,"")+'"]');if(!e.length)return;h.call(c,a.extend({remote:!/#/.test(c.attr('href'))&&c.attr('href')},e.data(),c.data()))}).on('render.bs.modal',function(b){a(b.target).one('click.dismiss.bs.modal',function(){a(b.target).modal('hide')})}).on('click.bs.modal.data-api','[data-dismiss="modal"]',function(b){var c=a(this).attr('data-target');c||(c=a(this).attr('href'),c=c&&c.replace(/.*\[#\](?=.*$)/,""));a(c||this).modal('hide')})}(jQuery),+function(a){'use strict';function b(b){return this.each(function(){var d=a(this),e=d.data('bs.tooltip'),f='object'==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data('bs.tooltip',e=new c(this,f)),'string'==typeof b&&e[b]()})}}var c=function(a,b){this.init('tooltip',a,b)};c.VERSION='3.3.5',c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:'top',selector:!1,template:'',trigger:'hover focus',title:'',delay:0,html:!1,container:!1,viewport:{selector:'body',padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(' '),f=e.length;f--;){var g=e[f];if('click'==g)this.$element.on('click.'+this.type,this.options.selector,a.proxy(this.toggle,this));else if('manual'!=g){var h='hover'==g?'mouseenter':'focusin',i='hover'==g?'mouseleave':'focusout';this.$element.on(h+'.'+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+'.'+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:'manual',selector:''}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&'number'==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data('bs.'+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data('bs.'+this.type,c)),b instanceof a.Event&&(c.inState['focusin'==b.type?'focus':'hover']=!0),c.tip().hasClass('in')||'in'==c.hoverState?void(c.hoverState='in'):(clearTimeout(c.timeout),c.hoverState='in',c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){'in'==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data('bs.'+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data('bs.'+this.type,c)),b instanceof a.Event&&(c.inState['focusout'==b.type?'focus':'hover']=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState='out',c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){'out'==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event('show.bs.'+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr('id',g),this.$element.attr('aria-describedby',g),this.options.animation&&f.addClass('fade');var h='function'==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/(auto)?/i,j=i.test(h);j&&(h=h.replace(i,'')||'top'),f.detach().css({top:0,left:0,display:'block'}).addClass(h).data('bs.'+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger('inserted.bs.'+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h='bottom'==h&&k.bottom+m>o.bottom?'top':'top'==h&&k.top-mo.width?'left':'left'==h&&k.left-l% freq(smoker) # Grouped frequencies with(tobacco, stby(smoker, gender, freq)) ``` -------------------------------- ### Build Dynamic Tabsets from HTML Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html A function that scans the DOM for sections with the .tabset class and transforms them into Bootstrap tab components. It handles tab navigation, content containers, and active state assignment. ```javascript window.buildTabsets = function(tocID) { function buildTabset(tabset) { var fade = tabset.hasClass("tabset-fade"); var pills = tabset.hasClass("tabset-pills"); var navClass = pills ? "nav-pills" : "nav-tabs"; var match = tabset.attr('class').match(/level(\d) /); if (match === null) return; var tabsetLevel = Number(match[1]); var tabLevel = tabsetLevel + 1; var tabs = tabset.find("div.section.level" + tabLevel); if (!tabs.length) return; var tabList = $(''); $(tabs[0]).before(tabList); var tabContent = $('
'); $(tabs[0]).before(tabContent); var activeTab = 0; tabs.each(function(i) { var tab = $(tabs[i]); var id = tab.attr('id'); if (tab.hasClass('active')) activeTab = i; $("div#" + tocID + " li a[href='#" + id + "']").parent().remove(); id = id.replace(/[.\/?&!#<>]/g, '').replace(/\s/g, '_'); tab.attr('id', id); var heading = tab.find('h' + tabLevel + ':first'); var headingText = heading.html(); heading.remove(); var a = $('' + headingText + ''); a.attr('href', '#' + id); a.attr('aria-controls', id); var li = $('
  • '); li.append(a); tabList.append(li); tab.attr('role', 'tabpanel'); tab.addClass('tab-pane'); tab.addClass('tabbed-pane'); if (fade) tab.addClass('fade'); tab.detach().appendTo(tabContent); }); $(tabList.children('li')[activeTab]).addClass('active'); var active = $(tabContent.children('div.section')[activeTab]); active.addClass('active'); if (fade) active.addClass('in'); if (tabset.hasClass("tabset-sticky")) tabset.rmarkdownStickyTabs(); } var tabsets = $("div.section.tabset"); tabsets.each(function(i) { buildTabset($(tabsets[i])); }); }; ``` -------------------------------- ### Include summarytools preamble in PDF documents using LaTeX Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Provides LaTeX code for a preamble file to properly include graphics and adjust image alignment when generating PDF documents with data frame summaries from the summarytools package. This requires LaTeX and the graphicx, adjustbox, and letltxmacro packages. The preamble can be included in the YAML header of an R Markdown document. ```LaTeX \usepackage{graphicx} \usepackage[export]{adjustbox} \usepackage{letltxmacro} \LetLtxMacro{\OldIncludegraphics}{\includegraphics} \renewcommand{\includegraphics}[2][]{\raisebox{0.5\height}% {\OldIncludegraphics[valign=t,#1]{#2}}} ``` -------------------------------- ### JavaScript Selector Engine - Pseudo-class Handlers Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Provides implementations for various pseudo-class selectors like :not, :has, :contains, :lang, :target, :root, :focus, :enabled, :disabled, :checked, :selected, :empty, :parent, :header, :input, :button, :text, :first, :last, :eq, and :even. These allow for complex DOM querying based on element state, attributes, and relationships. ```javascript b.pseudos={ not:le(function(e){var r=[],i=[],s=f(e.replace($,"$1"));return s[S]?le(function(e,t,n,r){var i,o=s(e,null,r,[]);while(a--)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}), has:le(function(t){return function(e){return 0% group_by(gender) %>% dfSummary() ``` -------------------------------- ### Include summarytools CSS Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Injects the necessary CSS for summarytools into the R Markdown document to ensure proper styling of generated tables and summaries. ```R st_css(main = TRUE, global = TRUE) ``` -------------------------------- ### Bootstrap Popover Plugin Constructor Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Defines the constructor for the Bootstrap popover plugin, which extends the tooltip functionality. It includes specific options for popovers like placement, trigger, and content. ```javascript function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})} ``` -------------------------------- ### Bootstrap Popover Plugin Defaults Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Sets the default configuration options for the Bootstrap popover plugin. These defaults can be overridden when initializing a popover instance. ```javascript c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}) ``` -------------------------------- ### R: Generate Baseline Data Summary with dfSummary Source: https://github.com/dcomtois/summarytools/blob/master/doc/Custom-Statistics-in-dfSummary.html Generates a baseline summary of a subset of the iris dataset using the dfSummary function. The output is rendered in a specific format, likely for display in a report. ```r iri <- iris[3:5] print(dfSummary(iri, graph.magnif = .85), method = "render") ``` -------------------------------- ### Frequency Table with Render Method (R) Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Generates a frequency table for a factor variable using the 'render' method. This method is generally reliable for displaying results in R Markdown documents and supports HTML rendering. ```r print(freq(tobacco$gender), method = 'render') ``` -------------------------------- ### Implement Document Traversal Helper Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html A utility function to safely retrieve elements by tag name or class, ensuring compatibility across different document types and browser environments. ```javascript function ye(e) { return e && "undefined" != typeof e.getElementsByTagName && e; } function se(t, e, n, r) { var i, o, a, s, u, l, c, f = e && e.ownerDocument, p = e ? e.nodeType : 9; if (n = n || [], "string" != typeof t || !t || 1 !== p && 9 !== p && 11 !== p) return n; return g(t.replace($, "$1"), e, n, r); } ``` -------------------------------- ### Frequency Table with Pander Method (R) Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html Generates a frequency table for a factor variable using the 'pander' method and 'rmarkdown' style. This method is suitable for R Markdown documents and requires `plain.ascii = FALSE` for proper formatting. ```r freq(tobacco$gender, plain.ascii = FALSE, style = 'rmarkdown') ``` -------------------------------- ### Apply Bootstrap Styles to Pandoc Tables Source: https://github.com/dcomtois/summarytools/blob/master/doc/rmarkdown.html A JavaScript utility to dynamically apply Bootstrap table classes to Pandoc-generated tables within the document. ```JavaScript function bootstrapStylePandocTables() { $("tr.odd").parent("tbody").parent("table").addClass("table table-condensed"); } $(document).ready(function () { bootstrapStylePandocTables(); }); ``` -------------------------------- ### Perform Cross-Tabulation with ctable Source: https://context7.com/dcomtois/summarytools/llms.txt Generates cross-tabulation tables for categorical variables with options for proportions, totals, and statistical tests like chi-square, odds ratios, and risk ratios. ```R library(summarytools) data(tobacco) # Basic cross-tabulation with(tobacco, ctable(gender, smoker)) # With chi-square test and odds ratio with(tobacco, ctable(smoker, diseased, chisq = TRUE, OR = TRUE, RR = TRUE)) ```