-
Notifications
You must be signed in to change notification settings - Fork 221
Expand file tree
/
Copy pathhelpers.R
More file actions
3622 lines (3416 loc) · 110 KB
/
helpers.R
File metadata and controls
3622 lines (3416 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#------------------------------------------------------------------------------#
#
# /$$
# | $$
# /$$$$$$ /$$$$$$
# /$$__ $$|_ $$_/
# | $$ \ $$ | $$
# | $$ | $$ | $$ /$$
# | $$$$$$$ | $$$$/
# \____ $$ \___/
# /$$ \ $$
# | $$$$$$/
# \______/
#
# This file is part of the 'rstudio/gt' project.
#
# Copyright (c) 2018-2025 gt authors
#
# For full copyright and license information, please look at
# https://gt.rstudio.com/LICENSE.html
#
#------------------------------------------------------------------------------#
# md() -------------------------------------------------------------------------
#' Interpret input text as Markdown-formatted text
#'
#' @description
#'
#' Markdown text can be used in certain places in a **gt** table, and this is
#' wherever new text is defined (e.g., footnotes, source notes, the table title,
#' etc.). Using Markdown is advantageous for styling text since it will be
#' rendered correctly to the output format of the **gt** table. There is
#' also the [html()] helper that allows you use HTML exclusively (for tables
#' expressly meant for HTML output) but `md()` allows for both; you get to use
#' Markdown plus any HTML fragments at the same time.
#'
#' @param text *Markdown text*
#'
#' `scalar<character>` // **required**
#'
#' The text that is understood to contain Markdown formatting.
#'
#' @return A character object of class `from_markdown`. It's tagged as being
#' Markdown text and it will undergo conversion to the desired output context.
#'
#' @section Examples:
#'
#' Use the [`exibble`] dataset to create a **gt** table. When adding a title
#' through [tab_header()], we'll use the `md()` helper to signify to **gt** that
#' we're using Markdown formatting.
#'
#' ```r
#' exibble |>
#' dplyr::select(currency, char) |>
#' gt() |>
#' tab_header(title = md("Using *Markdown*"))
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_md_1.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-1
#'
#' @section Function Introduced:
#' `v0.2.0.5` (March 31, 2020)
#'
#' @export
md <- function(text) {
# Apply the `from_markdown` class
class(text) <- "from_markdown"
text
}
# html() -----------------------------------------------------------------------
#' Interpret input text as HTML-formatted text
#'
#' @description
#'
#' For certain pieces of text (like in column labels or table headings) we may
#' want to express them as raw HTML. In fact, with HTML, anything goes so it can
#' be much more than just text. The `html()` function will guard the input HTML
#' against escaping, so, your HTML tags will come through as HTML when
#' rendered... to HTML.
#'
#' @param text *HTML text*
#'
#' `scalar<character>` // **required**
#'
#' The text that is understood to be HTML text, which is to be preserved in
#' the HTML output context.
#'
#' @param ... *Optional parameters for `htmltools::HTML()`*
#'
#' `<multiple expressions>` // (`optional`)
#'
#' The `htmltools::HTML()` function contains `...` and anything provided here
#' will be passed to that internal function call.
#'
#' @return A character object of class `html`. It's tagged as an HTML fragment
#' that is not to be sanitized.
#'
#' @section Examples:
#'
#' Use the [`exibble`] dataset to create a **gt** table. When adding a title
#' through [tab_header()], we'll use the `html()` helper to signify to **gt**
#' that we're using HTML formatting.
#'
#' ```r
#' exibble |>
#' dplyr::select(currency, char) |>
#' gt() |>
#' tab_header(title = html("<em>HTML</em>"))
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_html_1.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-2
#'
#' @section Function Introduced:
#' `v0.2.0.5` (March 31, 2020)
#'
#' @export
html <- function(text, ...) {
if (inherits(text, "shiny.tag.list")) {
text <- as.character(text)
}
htmltools::HTML(text, ...)
}
# latex() -----------------------------------------------------------------------
#' Interpret input text as LaTeX-formatted text
#'
#' @description
#'
#' For certain pieces of text (like in column labels or table headings) we may
#' want to express them as raw LaTeX. In fact, with LaTeX, so much more can be done for formatting.
#' The `latex()` function will guard the input LaTeX from being escaped.
#'
#' @param text *LaTeX text*
#'
#' `scalar<character>` // **required**
#'
#' The text that is understood to be LaTeX text, which is to be preserved in
#' the LaTeX output context.
#'
#'
#' @return A character object of class `latex`. It's tagged as an latex fragment
#' that is not to be sanitized.
#'
#' @section Examples:
#'
#' Use the [`exibble`] dataset to create a **gt** table. When adding a title
#' through [tab_header()], we'll use the `latex()` helper to signify to **gt**
#' that we're using LaTeX formatting.
#'
#' ```r
#' exibble |>
#' dplyr::select(currency, char) |>
#' gt() |>
#' tab_header(title = latex("\\emph{LaTeX}"))
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_latex_1.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-2
#'
#' @section Function Introduced:
#' `v1.0.1` (May 10, 2025)
#'
#' @export
latex <- function(text) {
# Apply the `from_latex` class
class(text) <- "from_latex"
text
}
# px() -------------------------------------------------------------------------
#' Helper for providing a numeric value as pixels value
#'
#' @description
#'
#' For certain parameters, a length value is required. Examples include the
#' setting of font sizes (e.g., in [cell_text()]) and thicknesses of lines
#' (e.g., in [cell_borders()]). Setting a length in pixels with `px()` allows
#' for an absolute definition of size as opposed to the analogous helper
#' function [pct()].
#'
#' @param x *Numeric length in pixels*
#'
#' `scalar<numeric|integer>` // **required**
#'
#' The numeric value to format as a string (e.g., `"12px"`) for some
#' [tab_options()] arguments that can take values as units of pixels (e.g.,
#' `table.font.size`).
#'
#' @return A character vector with a single value in pixel units.
#'
#' @section Examples:
#'
#' Use the [`exibble`] dataset to create a **gt** table. Inside of the
#' [cell_text()] call (which is itself inside of [tab_style()]), we'll use the
#' `px()` helper function to define the font size for the column labels in units
#' of pixels.
#'
#' ```r
#' exibble |>
#' gt() |>
#' tab_style(
#' style = cell_text(size = px(20)),
#' locations = cells_column_labels()
#' )
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_px_1.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-3
#'
#' @section Function Introduced:
#' `v0.2.0.5` (March 31, 2020)
#'
#' @export
px <- function(x) {
if (mode(x) != "numeric") {
cli::cli_abort("The supplied value must be numeric.")
}
paste0(x, "px")
}
# pct() ------------------------------------------------------------------------
#' Helper for providing a numeric value as percentage
#'
#' @description
#'
#' A percentage value acts as a length value that is relative to an initial
#' state. For instance an 80 percent value for something will size the target
#' to 80 percent the size of its 'previous' value. This type of sizing is
#' useful for sizing up or down a length value with an intuitive measure. This
#' helper function can be used for the setting of font sizes (e.g., in
#' [cell_text()]) and altering the thicknesses of lines (e.g., in
#' [cell_borders()]). Should a more exact definition of size be required, the
#' analogous helper function [pct()] will be more useful.
#'
#' @param x *Numeric value in percent*
#'
#' `scalar<numeric|integer>` // **required**
#'
#' The numeric value to format as a string percentage for some [tab_options()]
#' arguments that can take percentage values (e.g., `table.width`).
#'
#' @return A character vector with a single value in percentage units.
#'
#' @section Examples:
#'
#' Use the [`exibble`] dataset to create a **gt** table. Inside of the
#' [cell_text()] call (which is itself inside of [tab_style()]), we'll use the
#' `pct()` helper function to define the font size for the column labels as a
#' percentage value.
#'
#' ```r
#' exibble |>
#' gt() |>
#' tab_style(
#' style = cell_text(size = pct(75)),
#' locations = cells_column_labels()
#' )
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_pct_1.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-4
#'
#' @section Function Introduced:
#' `v0.2.0.5` (March 31, 2020)
#'
#' @export
pct <- function(x) {
if (mode(x) != "numeric") {
cli::cli_abort("The supplied value must be numeric.")
}
paste0(x, "%")
}
# from_column() ----------------------------------------------------------------
#' Reference a column of values for certain parameters
#'
#' @description
#'
#' It can be useful to obtain parameter values from a column in a
#' **gt** for functions that operate on the table body and stub cells. For
#' example, you might want to indent row labels in the stub. You could call
#' [tab_stub_indent()] and indent different rows to various indentation levels.
#' However, each level of indentation applied necessitates a new call of that
#' function. To make this better, we can use indentation values available in a
#' table column via the `from_column()` helper function. For the
#' [tab_stub_indent()] case, you'd invoke this helper at the `indent` argument
#' and specify the column that has the values.
#'
#' @param column *Column name*
#'
#' `scalar<character>` // **required**
#'
#' A single column name in quotation marks. Values will be extracted from this
#' column and provided to compatible arguments.
#'
#' @param na_value *Default replacement for `NA` values*
#'
#' `scalar<character|numeric|logical>` // *default:* `NULL` (`optional`)
#'
#' A single value to replace any `NA` values in the `column`. Take care to
#' provide a value that is of the same type as the `column` values to avoid
#' any undesirable coercion.
#'
#' @param fn *Function to apply*
#'
#' `function|formula` // *default:* `NULL` (`optional`)
#'
#' If a function is provided here, any values extracted from the table
#' `column` (except `NA` values) can be mutated.
#'
#' @return A list object of class `gt_column`.
#'
#' @section Functions that allow the use of the `from_column()` helper:
#'
#' Only certain functions (and furthermore a subset of arguments within each)
#' support the use of `from_column()` for accessing varying parameter values.
#' These functions are:
#'
#' - [tab_stub_indent()]
#' - [fmt_number()]
#' - [fmt_integer()]
#' - [fmt_scientific()]
#' - [fmt_engineering()]
#' - [fmt_percent()]
#' - [fmt_partsper()]
#' - [fmt_fraction()]
#' - [fmt_currency()]
#' - [fmt_roman()]
#' - [fmt_index()]
#' - [fmt_spelled_num()]
#' - [fmt_bytes()]
#' - [fmt_date()]
#' - [fmt_time()]
#' - [fmt_datetime()]
#' - [fmt_url()]
#' - [fmt_image()]
#' - [fmt_flag()]
#' - [fmt_markdown()]
#' - [fmt_passthrough()]
#'
#' Within help documents for each of these functions you'll find the
#' *Compatibility of arguments with the `from_column()` helper function* section
#' and sections like these describe which arguments support the use of
#' `from_column()`.
#'
#' @section Examples:
#'
#' `from_column()` can be used in a variety of formatting functions so that
#' values for common options don't have to be static, they can change in every
#' row (so long as you have a column of compatible option values). Here's an
#' example where we have a table of repeating numeric values along with a column
#' of currency codes. We can format the numbers to currencies with
#' [fmt_currency()] and use `from_column()` to reference the column of currency
#' codes, giving us values that are each formatted as having a different
#' currency.
#'
#' ```r
#' dplyr::tibble(
#' amount = rep(30.75, 6),
#' curr = c("USD", "EUR", "GBP", "CAD", "AUD", "JPY"),
#' ) |>
#' gt() |>
#' fmt_currency(currency = from_column(column = "curr"))
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_from_column_1.png")`
#' }}
#'
#' Let's summarize the [`gtcars`] dataset to get a set of rankings of car
#' manufacturer by country of origin. The `n` column represents the number of
#' cars a manufacturer has within this dataset and we can use that column as a
#' way to size the text. We do that in the [tab_style()] call; the
#' `from_column()` function is used within the [cell_text()] statement to
#' fashion different font sizes from that `n` column. This is done in
#' conjunction with the `fn` argument of `from_column()`, which helps to tweak
#' the values in `n` to get a useful range of font sizes.
#'
#' ```r
#' gtcars |>
#' dplyr::count(mfr, ctry_origin) |>
#' dplyr::arrange(ctry_origin) |>
#' gt(groupname_col = "ctry_origin") |>
#' tab_style(
#' style = cell_text(
#' size = from_column(
#' column = "n",
#' fn = function(x) paste0(5 + (x * 3), "px")
#' )
#' ),
#' locations = cells_body()
#' ) |>
#' tab_style(
#' style = cell_text(align = "center"),
#' locations = cells_row_groups()
#' ) |>
#' cols_hide(columns = n) |>
#' tab_options(column_labels.hidden = TRUE) |>
#' opt_all_caps() |>
#' opt_vertical_padding(scale = 0.25) |>
#' cols_align(align = "center", columns = mfr)
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_from_column_2.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-5
#'
#' @section Function Introduced:
#' `v0.10.0` (October 7, 2023)
#'
#' @export
from_column <- function(
column,
na_value = NULL,
fn = NULL
) {
column_list <-
list(
column = column,
na_value = na_value[1],
fn = fn
)
# Set the `gt_currency` class
class(column_list) <- "gt_column"
column_list
}
# currency() -------------------------------------------------------------------
#' Supply a custom currency symbol to `fmt_currency()`
#'
#' @description
#'
#' The `currency()` helper function makes it easy to specify a context-aware
#' currency symbol to `currency` argument of [fmt_currency()]. Since **gt** can
#' render tables to several output formats, `currency()` allows for different
#' variations of the custom symbol based on the output context (which are
#' `html`, `latex`, `rtf`, and `default`). The number of decimal places for
#' the custom currency defaults to `2`, however, a value set for the `decimals`
#' argument of [fmt_currency()] will take precedence.
#'
#' @details
#'
#' We can use any combination of `html`, `latex`, `rtf`, and `default` as named
#' arguments for the currency text in each of the namesake contexts. The
#' `default` value is used as a fallback when there doesn't exist a dedicated
#' currency text value for a particular output context (e.g., when a table is
#' rendered as HTML and we use `currency(latex = "LTC", default = "ltc")`, the
#' currency symbol will be `"ltc"`. For convenience, if we provide only a single
#' string without a name, it will be taken as the `default` (i.e.,
#' `currency("ltc")` is equivalent to `currency(default = "ltc")`). However, if
#' we were to specify currency strings for multiple output contexts, names are
#' required each and every context.
#'
#' @param ... *Currency symbols by output context*
#'
#' `<named arguments>` // **required** (or, use `.list`)
#'
#' One or more named arguments using output contexts as the names and
#' currency symbol text as the values.
#'
#' @param .list *Alternative to `...`*
#'
#' `<list of multiple expressions>` // **required** (or, use `...`)
#'
#' Allows for the use of a list as an input alternative to `...`.
#'
#' @return A list object of class `gt_currency`.
#'
#' @section Examples:
#'
#' Use the [`exibble`] dataset to create a **gt** table. Within the
#' [fmt_currency()] call, we'll format the `currency` column to have currency
#' values in guilder (a defunct Dutch currency). We can register this custom
#' currency with the `currency()` helper function, supplying the `"ƒ"` HTML
#' entity for `html` outputs and using `"f"` for any other type of **gt**
#' output.
#'
#' ```r
#' exibble |>
#' gt() |>
#' fmt_currency(
#' columns = currency,
#' currency = currency(
#' html = "ƒ",
#' default = "f"
#' ),
#' decimals = 2
#' )
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_currency_1.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-6
#'
#' @section Function Introduced:
#' `v0.2.0.5` (March 31, 2020)
#'
#' @export
currency <- function(
...,
.list = list2(...)
) {
# Collect a named list of currencies
currency_list <- .list
# Stop function if the currency list contains no values
if (length(currency_list) == 0) {
cli::cli_abort(
"The `currency()` function must be provided with currency symbols."
)
}
# If only a single string is provided, upgrade the `currency_list`
# to have that string be the `default` value
if (length(currency_list) == 1 && !rlang::is_named(currency_list)) {
currency_list <- list(default = currency_list[[1]])
}
# Stop function if `currency_list` isn't entirely named
if (!rlang::is_named(currency_list)) {
cli::cli_abort("Names must be provided for all output contexts.")
}
# Stop function if all names are not part of the supported contexts
validate_contexts(contexts = names(currency_list))
# Stop function if there are duplicated names
if (!rlang::is_dictionaryish(currency_list)) {
cli::cli_abort("There cannot be any duplicate names for output contexts.")
}
# Set the `gt_currency` class
class(currency_list) <- "gt_currency"
currency_list
}
# unit_conversion() ------------------------------------------------------------
#' Get a conversion factor across two measurement units of a given class
#'
#' @description
#'
#' The `unit_conversion()` helper function gives us a conversion factor for
#' transforming a value from one form of measurement units to a target form.
#' For example if you have a length value that is expressed in miles you could
#' transform that value to one in kilometers through multiplication of the value
#' by the conversion factor (in this case `1.60934`).
#'
#' For `unit_conversion()` to understand the source and destination units, you
#' need to provide a keyword value for the `from` and `to` arguments. To aid as
#' a reference for this, call [info_unit_conversions()] to display an
#' information table that contains all of the keywords for every conversion
#' type.
#'
#' @param from *Units for the input value*
#'
#' `scalar<character>` // **required**
#'
#' The keyword representing the units for the value that requires unit
#' conversion. In the case where the value has units of miles, the necessary
#' input is `"length.mile"`.
#'
#' @param to *Desired units for the value*
#'
#' `scalar<character>` // **required**
#'
#' The keyword representing the target units for the value with units defined
#' in `from`. In the case where input value has units of miles and we would
#' rather want the value to be expressed as kilometers, the `to` value should
#' be `"length.kilometer"`.
#'
#' @return A single numerical value.
#'
#' @section Examples:
#'
#' Let's use a portion of the [`towny`] dataset and create a table showing
#' population, density, and land area for 10 municipalities. The `land_area_km2`
#' values are in units of square kilometers, however, we'd rather the values
#' were in square miles. We can convert the numeric values while formatting the
#' values with [`fmt_number()`] by using `unit_conversion()` in the `scale_by`
#' argument since the return value of that is a conversion factor (which is
#' applied to each value by multiplication). The same is done for converting the
#' 'people per square kilometer' values in `density_2021` to 'people per square
#' mile', however, the units to convert are in the denominator so the inverse
#' of the conversion factor must be used.
#'
#' ```r
#' towny |>
#' dplyr::slice_max(density_2021, n = 10) |>
#' dplyr::select(name, population_2021, density_2021, land_area_km2) |>
#' gt(rowname_col = "name") |>
#' fmt_integer(columns = population_2021) |>
#' fmt_number(
#' columns = land_area_km2,
#' decimals = 1,
#' scale_by = unit_conversion(
#' from = "area.square-kilometer",
#' to = "area.square-mile"
#' )
#' ) |>
#' fmt_number(
#' columns = density_2021,
#' decimals = 1,
#' scale_by = 1 / unit_conversion(
#' from = "area.square-kilometer",
#' to = "area.square-mile"
#' )
#' ) |>
#' cols_label(
#' land_area_km2 = "Land Area,<br>sq. mi",
#' population_2021 = "Population",
#' density_2021 = "Density,<br>ppl / sq. mi",
#' .fn = md
#' )
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_unit_conversion_1.png")`
#' }}
#'
#' With a small slice of the [`gibraltar`] dataset, let's display the
#' temperature values in terms of degrees Celsius (present in the data) *and* as
#' temperatures in degrees Fahrenheit (achievable via conversion). We can
#' duplicate the `temp` column through [cols_add()] (naming the new column as
#' `temp_f`) and when formatting through [fmt_integer()] we can call
#' `unit_conversion()` within the `scale_by` argument to perform this
#' transformation while formatting the values as integers.
#'
#' ```r
#' gibraltar |>
#' dplyr::filter(
#' date == "2023-05-15",
#' time >= "06:00",
#' time <= "12:00"
#' ) |>
#' dplyr::select(time, temp) |>
#' gt() |>
#' tab_header(
#' title = "Air Temperature During Late Morning Hours at LXGB Stn.",
#' subtitle = "May 15, 2023"
#' ) |>
#' cols_add(temp_f = temp) |>
#' cols_move(columns = temp_f, after = temp) |>
#' tab_spanner(
#' label = "Temperature",
#' columns = starts_with("temp")
#' ) |>
#' fmt_number(
#' columns = temp,
#' decimals = 1
#' ) |>
#' fmt_integer(
#' columns = temp_f,
#' scale_by = unit_conversion(
#' from = "temperature.C",
#' to = "temperature.F"
#' )
#' ) |>
#' cols_label(
#' time = "Time",
#' temp = "{{degC}}",
#' temp_f = "{{degF}}"
#' ) |>
#' cols_width(
#' starts_with("temp") ~ px(80),
#' time ~ px(100)
#' ) |>
#' opt_horizontal_padding(scale = 3) |>
#' opt_vertical_padding(scale = 0.5) |>
#' opt_align_table_header(align = "left") |>
#' tab_options(heading.title.font.size = px(16))
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_unit_conversion_2.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-7
#'
#' @section Function Introduced:
#' `v0.11.0` (July 9, 2024)
#'
#' @export
unit_conversion <- function(from, to) {
force(from)
force(to)
if (from %in% temperature_keywords() && to %in% temperature_keywords()) {
from <- normalize_temp_keyword(from)
to <- normalize_temp_keyword(to)
return(temperature_conversions(from = from, to = to))
}
if (!(from %in% conversion_factors[["from"]])) {
cli::cli_abort("The unit supplied in {.arg from} is not known.")
}
if (!(to %in% conversion_factors[["to"]])) {
cli::cli_abort("The unit supplied in {.arg to} is not known.")
}
if (from == to) {
return(1.0)
}
row_conversion <-
vctrs::vec_slice(
conversion_factors,
conversion_factors$from == from &
conversion_factors$to == to
)
# In the case where units are valid and available in the internal dataset,
# they may be across categories; such pairings do not allow for a conversion
# to take place
if (nrow(row_conversion) == 0L) {
cli::cli_abort("The conversion specified cannot be performed.")
}
row_conversion[["conv_factor"]]
}
temperature_keywords <- function() {
c(
"temperature.celsius",
"temp.celsius",
"celsius",
"temperature.C",
"temp.C",
"C",
"temperature.fahrenheit",
"temp.fahrenheit",
"fahrenheit",
"temperature.F",
"temp.F",
"F",
"temperature.kelvin",
"temp.kelvin",
"kelvin",
"temperature.K",
"temp.K",
"K",
"temperature.rankine",
"temp.rankine",
"rankine",
"temperature.R",
"temp.R",
"R"
)
}
normalize_temp_keyword <- function(keyword) {
switch(
keyword,
temperature.celsius = ,
temp.celsius = ,
celsius = ,
temperature.C = ,
temp.C = ,
C = "C",
temperature.fahrenheit = ,
temp.fahrenheit = ,
fahrenheit = ,
temperature.F = ,
temp.F = ,
`F` = "F",
temperature.kelvin = ,
temp.kelvin = ,
kelvin = ,
temperature.K = ,
temp.K = ,
K = "K",
temperature.rankine = ,
temp.rankine = ,
rankine = ,
temperature.R = ,
temp.R = ,
R = "R"
)
}
temperature_conversions <- function(from, to) {
from_to <- paste0(from, to)
switch(
from_to,
"CF" = function(x) (1.8 * x) + 32,
"CK" = function(x) x + 273.15,
"CR" = function(x) (1.8 * x) + 491.67,
"FC" = function(x) (x - 32) * 5/9,
"FK" = function(x) (x + 459.67) / 1.8,
"FR" = function(x) x + 459.67,
"KC" = function(x) x - 273.15,
"KF" = function(x) ((x - 273.15) * 1.8) + 32,
"KR" = function(x) x * 1.8,
"RC" = function(x) (x - 32 - 459.67) / 1.8,
"RF" = function(x) x - 459.67,
"RK" = function(x) x / 1.8,
"CC" = ,
"FF" = ,
"KK" = ,
"RR" = 1
)
}
# adjust_luminance() -----------------------------------------------------------
#' Adjust the luminance for a palette of colors
#'
#' @description
#'
#' The `adjust_luminance()` function can brighten or darken a palette of colors
#' by an arbitrary number of steps, which is defined by a real number between
#' -2.0 and 2.0. The transformation of a palette by a fixed step in this
#' function will tend to apply greater darkening or lightening for those colors
#' in the midrange compared to any very dark or very light colors in the input
#' palette.
#'
#' @details
#'
#' This function can be useful when combined with the [data_color()] function's
#' `palette` argument, which can use a vector of colors or any of the `col_*`
#' functions from the **scales** package (all of which have a `palette`
#' argument).
#'
#' @param colors *Color vector*
#'
#' `vector<character>` // **required**
#'
#' This is the vector of colors that will undergo an adjustment in luminance.
#' Each color value provided must either be a color name (in the set of colors
#' provided by `grDevices::colors()`) or a hexadecimal string in the form of
#' "#RRGGBB" or "#RRGGBBAA".
#'
#' @param steps *Adjustment level*
#'
#' `scalar<numeric|integer>(-2>=val>=2)` // **required**
#'
#' A positive or negative factor by which the luminance of colors in the
#' `colors` vector will be adjusted. Must be a number between `-2.0` and
#' `2.0`.
#'
#' @return A vector of color values.
#'
#' @section Examples:
#'
#' Get a palette of 8 pastel colors from the **RColorBrewer** package.
#'
#' ```r
#' pal <- RColorBrewer::brewer.pal(8, "Pastel2")
#' ```
#'
#' Create lighter and darker variants of the base palette (one step lower, one
#' step higher).
#'
#' ```r
#' pal_darker <- pal |> adjust_luminance(-1.0)
#' pal_lighter <- pal |> adjust_luminance(+1.0)
#' ```
#'
#' Create a tibble and make a **gt** table from it. Color each column in order
#' of increasingly darker palettes (with [data_color()]).
#'
#' ```r
#' dplyr::tibble(a = 1:8, b = 1:8, c = 1:8) |>
#' gt() |>
#' data_color(
#' columns = a,
#' colors = scales::col_numeric(
#' palette = pal_lighter,
#' domain = c(1, 8)
#' )
#' ) |>
#' data_color(
#' columns = b,
#' colors = scales::col_numeric(
#' palette = pal,
#' domain = c(1, 8)
#' )
#' ) |>
#' data_color(
#' columns = c,
#' colors = scales::col_numeric(
#' palette = pal_darker,
#' domain = c(1, 8)
#' )
#' )
#' ```
#'
#' \if{html}{\out{
#' `r man_get_image_tag(file = "man_adjust_luminance_1.png")`
#' }}
#'
#' @family helper functions
#' @section Function ID:
#' 8-9
#'
#' @section Function Introduced:
#' `v0.2.0.5` (March 31, 2020)
#'
#' @export
adjust_luminance <- function(
colors,
steps
) {
# Stop if steps is beyond an acceptable range
check_number_decimal(steps, min = -2, max = 2)
# Get a matrix of values in the RGB color space
rgb_matrix <- t(grDevices::col2rgb(colors, alpha = TRUE)) / 255
# Obtain the alpha values
alpha <- rgb_matrix[, "alpha"]
# Get a matrix of values in the Luv color space
luv_matrix <- grDevices::convertColor(rgb_matrix[, 1:3], "sRGB", "Luv")
# Apply calculations to obtain values in the HCL color space
h <- atan2(luv_matrix[, "v"], luv_matrix[, "u"]) * 180 / pi
c <- sqrt(luv_matrix[, "u"]^2 + luv_matrix[, "v"]^2)
l <- luv_matrix[, "L"]
# Scale luminance to occupy [0, 1]
y <- l / 100.
# Obtain `x` positions of luminance values along a sigmoid function
x <- log(-(y / (y - 1)))
# Calculate new luminance values based on a fixed step-change in `x`
y_2 <- 1 / (1 + exp(-(x + steps)))
# Rescale the new luminance values to [0, 100]
l <- y_2 * 100.
# Obtain hexadecimal colors from the modified HCL color values
grDevices::hcl(h, c, l, alpha = alpha)
}
#' Select helper for targeting the stub column
#'
#' @description
#'
#' Should you need to target only the stub column for formatting or other
#' operations, the `stub()` select helper can be used. This obviates the need
#' to use the name of the column that was selected as the stub column.