Learn R Programming

pixiedust

After tidying up your analyses with the broom package, go ahead and grab the pixiedust. Customize your table output and write it to markdown, HTML, LaTeX, or even just the console. pixiedust makes it easy to customize the appearance of your tables in all of these formats by adding any number of “sprinkles”, much in the same way you can add layers to a ggplot.

fit <- lm(mpg ~ qsec + factor(am) + wt + factor(gear), data = mtcars)
library(pixiedust)
dust(fit) %>% 
  sprinkle(col = 2:4, round = 3) %>% 
  sprinkle(col = 5, fn = quote(pvalString(value))) %>% 
  sprinkle_colnames(term = "Term", 
                    estimate = "Estimate", 
                     std.error = "SE",
                     statistic = "T-statistic", 
                     p.value = "P-value") %>%
  sprinkle_print_method("console")
#>            Term Estimate    SE T-statistic P-value
#> 1   (Intercept)    9.365 8.373       1.118    0.27
#> 2          qsec    1.245 0.383       3.252   0.003
#> 3   factor(am)1    3.151 1.941       1.624    0.12
#> 4            wt   -3.926 0.743      -5.286 < 0.001
#> 5 factor(gear)4   -0.268 1.655      -0.162    0.87
#> 6 factor(gear)5    -0.27 2.063      -0.131     0.9

Customizing with Sprinkles

Tables can be customized by row, column, or even by a single cell by adding sprinkles to the dust object. The table below shows the currently planned and implemented sprinkles. In the “implemented” column, an ‘x’ indicates a customization that has been implemented, while a blank cell suggests that the customization is planned but has not yet been implemented. In the remaining columns, an ‘x’ indicates that the sprinkle is already implemented for the output format; an ‘o’ indicates that implementation is planned but not yet completed; and a blank cell indicates that the sprinkle will not be implemented (usually because the output format doesn’t support the option).

sprinkleimplementedconsolemarkdownhtmllatex
bgxxx
bg_patternxxx
bg_pattern_byxxx
boldxxxxx
bookdownxx
border_collapsexxx
borderxxx
border_thicknessxxx
border_unitsxxx
border_stylexxx
border_colorxxx
captionxxxxx
colnamesxxxxx
discretexxx
discrete_colorsxxx
floatxx
fnxxxxx
font_colorxxx
font_familyxx
font_sizexxx
font_size_unitsxxx
gradientxxx
gradient_colorsxxx
gradient_cutxxx
gradient_nxxx
gradient_naxxx
halignxxx
heightxxx
height_unitsxxx
hhlinexx
italicxxxxx
justifyxxx
labelxxx
longtablexxxxx
mergexxxxx
na_stringxxxxx
paddingxx
replacexxxxx
roundxxxxx
rotate_degreexxx
sanitizex
sanitize_argsx
tabcolsepx
valignxxx
widthxxx
width_unitsxxx

A Brief Example

To demonstrate, let’s look at a simple linear model. We build the model and generate the standard summary.

fit <- lm(mpg ~ qsec + factor(am) + wt + factor(gear), data = mtcars)

summary(fit)
#> 
#> Call:
#> lm(formula = mpg ~ qsec + factor(am) + wt + factor(gear), data = mtcars)
#> 
#> Residuals:
#>     Min      1Q  Median      3Q     Max 
#> -3.5064 -1.5220 -0.7517  1.3841  4.6345 
#> 
#> Coefficients:
#>               Estimate Std. Error t value Pr(>|t|)    
#> (Intercept)     9.3650     8.3730   1.118  0.27359    
#> qsec            1.2449     0.3828   3.252  0.00317 ** 
#> factor(am)1     3.1505     1.9405   1.624  0.11654    
#> wt             -3.9263     0.7428  -5.286 1.58e-05 ***
#> factor(gear)4  -0.2682     1.6555  -0.162  0.87257    
#> factor(gear)5  -0.2697     2.0632  -0.131  0.89698    
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> Residual standard error: 2.55 on 26 degrees of freedom
#> Multiple R-squared:  0.8498, Adjusted R-squared:  0.8209 
#> F-statistic: 29.43 on 5 and 26 DF,  p-value: 6.379e-10

While the summary is informative and useful, it is full of “stats-speak” and isn’t necessarily in a format that is suitable for publication or submission to a client. The broom package provides the summary in tidy format that, serendipitously, it a lot closer to what we would want for formal reports.

library(broom)
tidy(fit)
#> # A tibble: 6 × 5
#>   term          estimate std.error statistic   p.value
#>   <chr>            <dbl>     <dbl>     <dbl>     <dbl>
#> 1 (Intercept)      9.37      8.37      1.12  0.274    
#> 2 qsec             1.24      0.383     3.25  0.00317  
#> 3 factor(am)1      3.15      1.94      1.62  0.117    
#> 4 wt              -3.93      0.743    -5.29  0.0000158
#> 5 factor(gear)4   -0.268     1.66     -0.162 0.873    
#> 6 factor(gear)5   -0.270     2.06     -0.131 0.897

It has been observed by some, however, that even this summary isn’t quite ready for publication. There are too many decimal places, the p-value employ scientific notation, and column titles like “statistic” don’t specify what type of statistic. These kinds of details aren’t the purview of broom, however, as broom is focused on tidying the results of a model for further analysis (particularly with respect to comparing slightly varying models).

The pixiedust package diverts from broom’s mission here and provides the ability to customize the broom output for presentation. The initial dust object returns a table that is similar to the broom output.

library(pixiedust)
dust(fit) %>%
  sprinkle_print_method("console")
#>            term   estimate std.error  statistic   p.value
#> 1   (Intercept)  9.3650443 8.3730161  1.1184792 0.2735903
#> 2          qsec  1.2449212 0.3828479  3.2517387 0.0031681
#> 3   factor(am)1  3.1505178 1.9405171  1.6235455 0.1165367
#> 4            wt -3.9263022 0.7427562 -5.2861251  1.58e-05
#> 5 factor(gear)4  -0.268163 1.6554617 -0.1619868 0.8725685
#> 6 factor(gear)5 -0.2697468 2.0631829  -0.130743  0.896985

Where pixiedust shows its strength is the ease of which these tables can be customized. The code below rounds the columns estimate, std.error, and statistic to three decimal places each, and then formats the p.value into a format that happens to be one that I like.

x <- dust(fit) %>% 
  sprinkle(col = 2:4, round = 3) %>% 
  sprinkle(col = 5, fn = quote(pvalString(value))) %>%
  sprinkle_print_method("console")
x
#>            term estimate std.error statistic p.value
#> 1   (Intercept)    9.365     8.373     1.118    0.27
#> 2          qsec    1.245     0.383     3.252   0.003
#> 3   factor(am)1    3.151     1.941     1.624    0.12
#> 4            wt   -3.926     0.743    -5.286 < 0.001
#> 5 factor(gear)4   -0.268     1.655    -0.162    0.87
#> 6 factor(gear)5    -0.27     2.063    -0.131     0.9

Now we’re almost there! Let’s change up the column names, and while we’re add it, let’s add some “bold” markers to the statistically significant terms in order to make them stand out some (I say “bold” because the console output doesn’t show up in bold, but with the markdown tags for bold text. In a rendered table, the text would actually be rendered in bold).

x <- x %>% 
  sprinkle(col = c("estimate", "p.value"), 
           row = c(2, 4), 
           bold = TRUE) %>% 
  sprinkle_colnames(term = "Term", 
                estimate = "Estimate", 
                std.error = "SE",
                statistic = "T-statistic", 
                p.value = "P-value") %>%
  sprinkle_print_method("console")

x
#>            Term   Estimate    SE T-statistic     P-value
#> 1   (Intercept)    9.365   8.373       1.118      0.27  
#> 2          qsec  **1.245** 0.383       3.252   **0.003**
#> 3   factor(am)1    3.151   1.941       1.624      0.12  
#> 4            wt **-3.926** 0.743      -5.286 **< 0.001**
#> 5 factor(gear)4   -0.268   1.655      -0.162      0.87  
#> 6 factor(gear)5    -0.27   2.063      -0.131       0.9

A cool, free tip!

The markdown output from pixiedust is somewhat limited due to the limitations of Rmarkdown itself. If/when more features become available for Rmarkdown output, I’ll be sure to include them. But what can you do if you really want all of the flexibility of the HTML tables but need the MS Word document?

With a little help from the Gmisc package, you can have the best of both worlds. Gmisc isn’t available on CRAN yet, but if you’re willing to install it from GitHub, you can render a docx file. Install Gmisc with

install.packages("Gmisc")

Then use in your YAML header

---
output: Gmisc::docx_document
---

When you knit your document, it knits as an HTML file, but I’ve had no problems with the rendering when I right-click the file and open with MS Word.

Read more at http://gforge.se/2014/07/fast-track-publishing-using-rmarkdown/ (but note that this blog post was written about the Grmd package before it was moved into the Gmisc package).

Copy Link

Version

Install

install.packages('pixiedust')

Monthly Downloads

519

Version

0.9.4

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

October 10th, 2023

Functions in pixiedust (0.9.4)

pixie_count

Access and manipulate table numbers counters
sprinkle_bg

Sprinkle the Background Color of a Cell
sanitize_latex

Escape Characters for Printing in LaTeX Output
sprinkle_align

Sprinkle Alignment of Table Cells
sprinkle_bg_pattern

Row and Column Background Striping
sprinkle_caption

Change the Caption in a Dust Table
sprinkle_bookdown

Change the Bookdown Property in a Dust Table
sprinkle_border_collapse

Change the Border Collapse Property in a Dust Table
sprinkle_border

Sprinkle Changes to Cell Borders
reshape_data_internal

Reshape data frames for Pixiedust
sprinkle

Define Customizations to a Table
sprinkle_gradient

Change Color Features by Binning Numeric Values
sprinkle_colnames

Column Names for dust Tables
sprinkle_height

Adjust Table Cell Height
sprinkle_float

Change the float Property in a Dust Table
sprinkle_caption_number

Change the Caption in a Dust Table
sprinkle_fixed_header

Assign a Fixed Header to an HTML Table
sprinkle_fn

Apply a function to a selection of cells
sprinkle_discrete

Change Color Features by Discrete Values
sprinkle_hhline

Change the hhline Property in a Dust Table
sprinkle_font

Sprinkle the Characteristics of Text in a Cell
sprinkle_replace

Replace Contents of Selected Cells
sprinkle_html_preserve

Change the HTML Preserve Property in a Dust Table
sprinkle_na_string

Sprinkle Appearance of NA's
sprinkle_merge

Sprinkle Table Cells to Merge
sprinkle_pad

Sprinkle the Padding of a Cell
sprinkle_round

Sprinkle Appearance of NA's
sprinkle_rotate_degree

Sprinkle Appearance of NA's
sprinkle_justify

Change the Caption in a Dust Table
sprinkle_label

Change the Border Collapse Property in a Dust Table
tidy_levels_labels

Term and Level Descriptions for pixiedust Tables
sprinkle_width

Adjust Table Cell Width
str_extract_base

Extract Patterns from Character Strings
sprinkle_longtable

Change the Longtable Property in a Dust Table
sprinkle_tabcolsep

Change the tabcolsep Property in a Dust Table
sprinkle_sanitize

Sanitize Characters for LaTeX Outputs
fixed_header_css

Generate CSS Code for Fixed Header Tables
%<>%

Chain together multiple operations
%>%

magrittr forward-pipe operator
is_valid_color

Test a Character String For Pixiedust Recognized Color Format
index_to_sprinkle

Determine the Indices to Sprinkle
get_dust_part

Get a Portion of the Table Stored in a dust Object
dust

Dust Table Construction
as.data.frame.dust

Convert dust Object to Data Frame
gaze

Mimic Stargazer Output to Display Multiple Models
glance_foot

Prepare Glance Statistics for pixiedust Table Footer
pixiedust

Tables So Beautifully Fine-Tuned You Will Believe It's Magic.
print.dust

Print A dust Table
medley_all_borders

Apply Cell Borders to All Cells in a Region
pixiedust_print_method

Determine the Current Print Method
knit_print.dust

knitr Printing Function
pixieply

Apply Functions Over `dust_list` Objects
pval_string

Format P-values for Reports
rbind_internal

Bind Rows in Base R
medley

Sprinkle Medleys