-
Notifications
You must be signed in to change notification settings - Fork 79
/
examples.Rmd
2518 lines (2041 loc) · 63.5 KB
/
examples.Rmd
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
---
title: "Examples"
output:
html_document:
toc: true
toc_float:
smooth_scroll: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(reactable)
options(reactable.static = TRUE)
```
## Basic Usage
To create a data table, use `reactable()` on a data frame or matrix.
The table will be sortable and paginated by default:
```{r}
library(reactable)
reactable(iris)
```
### Column definitions
Columns can be customized by providing a named list of column definitions
created by `colDef()` to `columns`:
```{r}
reactable(
iris[1:5, ],
columns = list(
Sepal.Length = colDef(name = "Sepal Length"),
Sepal.Width = colDef(name = "Sepal Width"),
Species = colDef(align = "center")
)
)
```
For convenience, you can also specify a default `colDef()` to use for all
columns in `defaultColDef`:
```{r}
reactable(
iris[1:5, ],
defaultColDef = colDef(
header = function(value) gsub(".", " ", value, fixed = TRUE),
cell = function(value) format(value, nsmall = 1),
align = "center",
minWidth = 70,
headerStyle = list(background = "#f7f7f8")
),
columns = list(
Species = colDef(minWidth = 140) # overrides the default
),
bordered = TRUE,
highlight = TRUE
)
```
## Sorting
Tables are sortable by default. You can sort a column by clicking on its
header, or sort multiple columns by holding the shift key while sorting.
Sorting toggles between ascending and descending order by default. To clear
the sort, hold the shift key while sorting, and the sorting will additionally
toggle between ascending, descending, and unsorted order.
::: {.callout-note}
**Note:** Ascending order means the lowest, first, or earliest values will appear first.
Descending order means the largest, last, or latest values will appear first.
:::
### Default sorted columns
You can set the default sorted columns by providing a vector of column names
to `defaultSorted`:
```{r}
reactable(iris[48:52, ], defaultSorted = c("Species", "Petal.Length"))
```
You can also provide a named list to customize the default sort orders.
Use `"asc"` for ascending order, or `"desc"` for descending order:
```{r}
reactable(iris[48:52, ], defaultSorted = list(Species = "asc", Petal.Length = "desc"))
```
### Default sort order
Columns are sorted in ascending order first by default. To change the default sort
order for all columns in the table, set `defaultSortOrder` in `reactable()` to
`"asc"` for ascending order, or `"desc"` for descending order.
To change the sort order of an individual column, set `defaultSortOrder` in
its `colDef()` to `"asc"` or `"desc"`. The default sort order of the column takes
precedence over the table.
```{r}
reactable(
iris[48:52, ],
defaultSortOrder = "desc",
columns = list(
Species = colDef(defaultSortOrder = "asc")
),
defaultSorted = c("Species", "Petal.Length")
)
```
### Sort missing values last
You can ignore missing values when sorting by setting `sortNALast` on a column:
```{r}
reactable(
data.frame(
n = c(1, 2, 3, -Inf, Inf),
x = c(2, 3, 1, NA, NaN),
y = c("aa", "cc", "bb", NA, NA)
),
defaultColDef = colDef(sortNALast = TRUE),
defaultSorted = "x"
)
```
### No sorting
You can disable sorting by setting `sortable` to `FALSE` on the table or column.
When only some columns are sortable, it can help to indicate sortable
columns using `showSortable`:
```{r}
reactable(
iris[1:5, ],
sortable = FALSE,
showSortable = TRUE,
columns = list(
Petal.Width = colDef(sortable = TRUE),
Petal.Length = colDef(sortable = TRUE)
)
)
```
### Hide sort icons
You can hide sort icons by setting `showSortIcon` to `FALSE`. This is only
recommended when you want to use a [custom sort indicator](cookbook/cookbook.html#custom-sort-indicators).
```{r}
reactable(iris[1:5, ], showSortIcon = FALSE)
```
## Filtering
You can make columns filterable by setting `filterable = TRUE` in `reactable()`:
```{r}
data <- MASS::Cars93[1:20, c("Manufacturer", "Model", "Type", "AirBags", "Price")]
reactable(data, filterable = TRUE, minRows = 10)
```
To make specific columns filterable (or not), set `filterable` to `TRUE` or `FALSE` in `colDef()`:
```{r}
reactable(
data,
filterable = TRUE,
columns = list(
Price = colDef(filterable = FALSE)
),
defaultPageSize = 5
)
```
### Custom filtering
Column filtering can be customized using the `filterMethod` and `filterInput` arguments
in `colDef()`. See the [Custom Filtering](custom-filtering.html) guide for more details
and examples.
This example shows basic usage of a custom filter method, changing filtering
on the `Manufacturer` column to be case-sensitive rather than case-insensitive.
(Try filtering for "bmw" and then "BMW").
```{r}
data <- MASS::Cars93[, c("Manufacturer", "Model", "Type", "Price")]
reactable(
data,
columns = list(
Manufacturer = colDef(
filterable = TRUE,
# Filter by case-sensitive text match
filterMethod = JS("function(rows, columnId, filterValue) {
return rows.filter(function(row) {
return row.values[columnId].indexOf(filterValue) !== -1
})
}")
)
),
defaultPageSize = 5
)
```
## Searching
You can make the entire table searchable by setting `searchable = TRUE` in `reactable()`:
```{r}
data <- MASS::Cars93[1:20, c("Manufacturer", "Model", "Type", "AirBags", "Price")]
reactable(data, searchable = TRUE, minRows = 10)
```
### Custom searching
The table search method can be customized using the `searchMethod` argument in `reactable()`.
See the [Custom Filtering](custom-filtering.html) guide for details and examples.
## Pagination
You can change the default page size by configuring `defaultPageSize`:
```{r}
reactable(iris[1:6, ], defaultPageSize = 4)
```
You can also set the minimum rows per page using `minRows`. This may be
useful when rows don't completely fill the page, or if the table has filtering:
```{r}
reactable(iris[1:6, ], defaultPageSize = 4, minRows = 4, searchable = TRUE)
```
### Page size options
You can show a dropdown of page sizes for users to choose from using `showPageSizeOptions`.
The page size options can be customized through `pageSizeOptions`:
```{r}
reactable(
iris[1:12, ],
showPageSizeOptions = TRUE,
pageSizeOptions = c(4, 8, 12),
defaultPageSize = 4
)
```
### Alternative pagination types
You can use an alternative pagination type by setting `paginationType` to:
- `"jump"` to show a page jump
- `"simple"` to show previous/next buttons only
#### Page jump
```{r}
reactable(iris[1:50, ], paginationType = "jump", defaultPageSize = 4)
```
#### Simple
```{r}
reactable(iris[1:50, ], paginationType = "simple", defaultPageSize = 4)
```
### Hide page info
You can hide page info by setting `showPageInfo` to `FALSE`:
```{r}
reactable(iris[1:12, ], showPageInfo = FALSE, defaultPageSize = 4)
reactable(iris[1:12, ], showPageInfo = FALSE, showPageSizeOptions = TRUE, defaultPageSize = 4)
```
### Always show pagination
By default, pagination is hidden if the table only has one page. To keep the
pagination shown, set `showPagination` to `TRUE`. This is especially useful if
you want to keep the page info showing the number of rows in the table.
```{r}
reactable(iris[1:5, ], showPagination = TRUE)
```
### No pagination
Tables are paginated by default, but you can disable pagination by setting `pagination` to `FALSE`:
```{r}
reactable(iris[1:20, ], pagination = FALSE, highlight = TRUE, height = 250)
```
::: {.callout-tip}
**Tip:** Disabling pagination is not recommended for large tables with many
interactive elements (such as links, expand buttons, or selection checkboxes),
as that can make it difficult for keyboard users to navigate the page.
:::
## Grouping and Aggregation
You can group rows in a table by specifying one or more columns in `groupBy`:
```{r}
data <- MASS::Cars93[10:22, c("Manufacturer", "Model", "Type", "Price", "MPG.city")]
reactable(data, groupBy = "Manufacturer")
```
When rows are grouped, you can aggregate data in a column using an `aggregate` function:
```{r}
data <- MASS::Cars93[14:38, c("Type", "Price", "MPG.city", "DriveTrain", "Man.trans.avail")]
reactable(
data,
groupBy = "Type",
columns = list(
Price = colDef(aggregate = "max"),
MPG.city = colDef(aggregate = "mean", format = colFormat(digits = 1)),
DriveTrain = colDef(aggregate = "unique"),
Man.trans.avail = colDef(aggregate = "frequency")
)
)
```
You can use one of the built-in aggregate functions:
```r
colDef(aggregate = "sum") # Sum of numbers
colDef(aggregate = "mean") # Mean of numbers
colDef(aggregate = "max") # Maximum of numbers
colDef(aggregate = "min") # Minimum of numbers
colDef(aggregate = "median") # Median of numbers
colDef(aggregate = "count") # Count of values
colDef(aggregate = "unique") # Comma-separated list of unique values
colDef(aggregate = "frequency") # Comma-separated counts of unique values
```
Or a custom aggregate function in JavaScript:
```r
colDef(
aggregate = JS("
function(values, rows) {
// input:
// - values: an array of all values in the group
// - rows: an array of row data values for all rows in the group (optional)
//
// output:
// - an aggregated value, e.g. a comma-separated list
return values.join(', ')
}
")
)
```
### Multiple groups
```{r}
data <- data.frame(
State = state.name,
Region = state.region,
Division = state.division,
Area = state.area
)
reactable(
data,
groupBy = c("Region", "Division"),
columns = list(
Division = colDef(aggregate = "unique"),
Area = colDef(aggregate = "sum", format = colFormat(separators = TRUE))
),
bordered = TRUE
)
```
### Custom aggregate function
Custom aggregate functions are useful when none of the built-in aggregate functions
apply, or when you want to aggregate values from multiple columns. For example,
when calculating aggregate averages or percentages.
Within a custom aggregate function, you can access the values in the column using
the `values` argument, and the values in other columns using the `rows` argument:
```js
columns = list(
Price = colDef(
aggregate = JS("function(values, rows) {
values
// [46.8, 27.6, 57]
rows
// [
// { "Model": "Dynasty", "Manufacturer": "Dodge", "Price": 46.8, "Units": 2 },
// { "Model": "Colt", "Manufacturer": "Dodge", "Price": 27.6, "Units": 5 },
// { "Model": "Caravan", "Manufacturer": "Dodge", "Price": 57, "Units": 5 }
// ]
}")
)
)
```
Here's an example that calculates an aggregate average price by dividing the
the sum of two columns, `Price` and `Units`:
```{r, message=FALSE}
library(dplyr)
set.seed(10)
data <- sample_n(MASS::Cars93[23:40, ], 30, replace = TRUE) %>%
mutate(Price = Price * 3, Units = sample(1:5, 30, replace = TRUE)) %>%
mutate(Avg.Price = Price / Units) %>%
select(Model, Manufacturer, Price, Units, Avg.Price)
reactable(
data,
groupBy = "Manufacturer",
columns = list(
Price = colDef(aggregate = "sum", format = colFormat(currency = "USD")),
Units = colDef(aggregate = "sum"),
Avg.Price = colDef(
# Calculate the aggregate Avg.Price as `sum(Price) / sum(Units)`
aggregate = JS("function(values, rows) {
let totalPrice = 0
let totalUnits = 0
rows.forEach(function(row) {
totalPrice += row['Price']
totalUnits += row['Units']
})
return totalPrice / totalUnits
}"),
format = colFormat(currency = "USD")
)
)
)
```
### Include sub rows in pagination
By default, sub rows are excluded from pagination and always shown on the same
page when expanded. To include sub rows in pagination, you can set `paginateSubRows`
to `TRUE`. This is recommended for grouped tables with a large number of rows
where expanded rows may not all fit on one page.
```{r}
data <- MASS::Cars93[, c("Manufacturer", "Model", "Type", "Price", "MPG.city")]
reactable(data, groupBy = "Type", paginateSubRows = TRUE)
```
## Column Formatting
You can format data in a column by providing `colFormat()` options to the `format`
argument in `colDef()`.
The formatters for numbers, dates, times, and currencies are locale-sensitive and
automatically adapt to language preferences of the user's browser. This means, for
example, that users will see dates formatted in their own timezone or numbers formatted
in their own locale.
To use a specific locale for data formatting, provide a vector of BCP 47 language
tags in the `locales` argument. See a list of
[common BCP 47 language tags](https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oe376/6c085406-a698-4e12-9d4d-c3b0ee3dbc4a)
for reference.
::: {.callout-note}
**Note:** Column formatters change how data is displayed without affecting the underlying
data. Sorting, filtering, and grouping will still work on the original data.
:::
```{r}
data <- data.frame(
price_USD = c(123456.56, 132, 5650.12),
price_INR = c(350, 23208.552, 1773156.4),
number_FR = c(123456.56, 132, 5650.12),
temp = c(22, NA, 31),
percent = c(0.9525556, 0.5, 0.112),
date = as.Date(c("2019-01-02", "2019-03-15", "2019-09-22"))
)
reactable(data, columns = list(
price_USD = colDef(format = colFormat(prefix = "$", separators = TRUE, digits = 2)),
price_INR = colDef(format = colFormat(currency = "INR", separators = TRUE, locales = "hi-IN")),
number_FR = colDef(format = colFormat(locales = "fr-FR")),
temp = colDef(format = colFormat(suffix = " °C")),
percent = colDef(format = colFormat(percent = TRUE, digits = 1)),
date = colDef(format = colFormat(date = TRUE, locales = "en-GB"))
))
```
### Date formatting
```{r}
datetimes <- as.POSIXct(c("2019-01-02 3:22:15", "2019-03-15 09:15:55", "2019-09-22 14:20:00"),
tz = "America/New_York")
data <- data.frame(
datetime = datetimes,
date = datetimes,
time = datetimes,
time_24h = datetimes,
datetime_pt_BR = datetimes
)
reactable(data, columns = list(
datetime = colDef(format = colFormat(datetime = TRUE)),
date = colDef(format = colFormat(date = TRUE)),
time = colDef(format = colFormat(time = TRUE)),
time_24h = colDef(format = colFormat(time = TRUE, hour12 = FALSE)),
datetime_pt_BR = colDef(format = colFormat(datetime = TRUE, locales = "pt-BR"))
))
```
### Currency formatting
```{r}
data <- data.frame(
USD = c(12.12, 2141.213, 0.42, 1.55, 34414),
EUR = c(10.68, 1884.27, 0.37, 1.36, 30284.32),
INR = c(861.07, 152122.48, 29.84, 110, 2444942.63),
JPY = c(1280, 226144, 44.36, 164, 3634634.61),
MAD = c(115.78, 20453.94, 4.01, 15, 328739.73)
)
reactable(data, columns = list(
USD = colDef(
format = colFormat(currency = "USD", separators = TRUE, locales = "en-US")
),
EUR = colDef(
format = colFormat(currency = "EUR", separators = TRUE, locales = "de-DE")
),
INR = colDef(
format = colFormat(currency = "INR", separators = TRUE, locales = "hi-IN")
),
JPY = colDef(
format = colFormat(currency = "JPY", separators = TRUE, locales = "ja-JP")
),
MAD = colDef(
format = colFormat(currency = "MAD", separators = TRUE, locales = "ar-MA")
)
))
```
### Formatting aggregated cells
Column formatters apply to both standard and aggregated cells by default. If you
want to format aggregated cells separately, provide a named list of `cell` and
`aggregated` options:
```{r, eval=FALSE}
colDef(
format = list(
cell = colFormat(...), # Standard cells
aggregated = colFormat(...) # Aggregated cells
)
)
```
For example, only the aggregated `States` are formatted here:
```{r}
data <- data.frame(
States = state.name,
Region = state.region,
Area = state.area
)
reactable(
data,
groupBy = "Region",
columns = list(
States = colDef(
aggregate = "count",
format = list(
aggregated = colFormat(suffix = " states")
)
),
Area = colDef(
aggregate = "sum",
format = colFormat(suffix = " mi²", separators = TRUE)
)
)
)
```
### Displaying missing values
Missing values are ignored by formatters and shown as empty cells by default.
You can customize their display text by setting `na` on a column:
```{r}
reactable(
data.frame(
n = c(1, 2, NA, 4, 5),
x = c(55, 27, NA, NaN, 19),
y = c(1, NA, 0.25, 0.55, NA)
),
columns = list(
x = colDef(na = "–", format = colFormat(prefix = "$")),
y = colDef(na = "NA", format = colFormat(percent = TRUE))
)
)
```
### Custom data formatting
If none of the built-in formatters apply to your data, you can use a
[custom cell renderer](#cell-rendering) instead.
## Custom Rendering
You can customize how data is displayed using an R or JavaScript function
that returns custom content. R render functions support
[Shiny HTML tags](https://shiny.rstudio.com/articles/tag-glossary.html) (or
[`htmltools`](https://unleash-shiny.rinterface.com/htmltools-overview.html)) and
[HTML widgets](https://www.htmlwidgets.org/),
while JavaScript render functions allow for more dynamic behavior.
You can also render content as HTML using `colDef(html = TRUE)`. Note that all
raw HTML is escaped by default.
See [Custom Rendering](custom-rendering.html) for details on how to
use render functions, and the [Demo Cookbook](cookbook/cookbook.html)
for even more examples of custom rendering.
::: {.callout-note}
**Note:** Custom rendering changes how data is displayed without affecting the underlying
data. Sorting, filtering, and grouping will still work on the original data.
:::
### Cell rendering
#### R render function
```{r}
data <- MASS::Cars93[1:5, c("Manufacturer", "Model", "Type", "AirBags", "Price")]
reactable(data, columns = list(
Model = colDef(cell = function(value, index) {
# Render as a link
url <- sprintf("https://wikipedia.org/wiki/%s_%s", data[index, "Manufacturer"], value)
htmltools::tags$a(href = url, target = "_blank", as.character(value))
}),
AirBags = colDef(cell = function(value) {
# Render as an X mark or check mark
if (value == "None") "\u274c No" else "\u2714\ufe0f Yes"
}),
Price = colDef(cell = function(value) {
# Render as currency
paste0("$", format(value * 1000, big.mark = ","))
})
))
```
#### JavaScript render function
```{r}
data <- MASS::Cars93[1:5, c("Manufacturer", "Model", "Type", "AirBags", "Price")]
reactable(data, columns = list(
Model = colDef(html = TRUE, cell = JS('
function(cellInfo) {
// Render as a link
const url = `https://wikipedia.org/wiki/${cellInfo.row["Manufacturer"]}_${cellInfo.value}`
return `<a href="${url}" target="_blank">${cellInfo.value}</a>`
}
')),
AirBags = colDef(cell = JS("
function(cellInfo) {
// Render as an X mark or check mark
return cellInfo.value === 'None' ? '\u274c No' : '\u2714\ufe0f Yes'
}
")),
Price = colDef(cell = JS("
function(cellInfo) {
// Render as currency
return '$' + (cellInfo.value * 1000).toLocaleString()
}
"))
))
```
#### Embedding HTML widgets
```{r message=FALSE}
library(dplyr)
library(sparkline)
data <- chickwts %>%
group_by(feed) %>%
summarise(weight = list(weight)) %>%
mutate(boxplot = NA, sparkline = NA)
reactable(data, columns = list(
weight = colDef(cell = function(values) {
sparkline(values, type = "bar", chartRangeMin = 0, chartRangeMax = max(chickwts$weight))
}),
boxplot = colDef(cell = function(value, index) {
sparkline(data$weight[[index]], type = "box")
}),
sparkline = colDef(cell = function(value, index) {
sparkline(data$weight[[index]])
})
))
```
### Grouped cell rendering
```{r}
data <- MASS::Cars93[10:22, c("Manufacturer", "Model", "Type", "Price", "MPG.city")]
reactable(
data,
groupBy = c("Manufacturer", "Type"),
columns = list(
Manufacturer = colDef(
# Render grouped cells without the row count
grouped = JS("function(cellInfo) {
return cellInfo.value
}")
),
Type = colDef(
# Render grouped cells with the row count, only if there are multiple sub rows
grouped = JS("function(cellInfo) {
if (cellInfo.subRows.length > 1) {
return cellInfo.value + ' (' + cellInfo.subRows.length + ')'
}
return cellInfo.value
}")
)
)
)
```
### Aggregated cell rendering
```{r, message=FALSE}
library(dplyr)
set.seed(10)
data <- sample_n(tail(MASS::Cars93, 9), 30, replace = TRUE) %>%
select(Manufacturer, Model, Type, Sales = Price)
reactable(
data,
groupBy = "Manufacturer",
searchable = TRUE,
columns = list(
Model = colDef(aggregate = "unique"),
Type = colDef(
# Render aggregated value as a comma-separated list of unique values
aggregated = JS("function(cellInfo) {
const values = cellInfo.subRows.map(function(row) { return row['Type'] })
const unique = values.reduce(function(obj, v) { obj[v] = true; return obj }, {})
return Object.keys(unique).join(', ')
}")
),
Sales = colDef(
aggregate = "sum",
# Render aggregated cell as currency
aggregated = JS("function(cellInfo) {
return cellInfo.value.toLocaleString('en-US', { style: 'currency', currency: 'USD' })
}")
)
)
)
```
### Header rendering
::: {.callout}
This example requires reactable v0.3.0 or above.
:::
```{r}
library(htmltools)
reactable(
iris[1:5, ],
defaultColDef = colDef(header = function(value) {
units <- div(style = "color: #737373", "cm")
div(title = value, value, units)
}),
columns = list(
Petal.Width = colDef(
name = "Petal Width",
html = TRUE,
align = "left",
header = JS('function(column) {
return column.name + `<div style="color: #737373">cm</div>`
}')
),
Species = colDef(header = function(value) {
tags$a(href = "https://wikipedia.org/wiki/List_of_Iris_species", value)
})
)
)
```
### Custom metadata {#custom-meta-rendering}
::: {.callout}
New in v0.4.0
:::
You can pass arbitrary data from R to JavaScript render functions using the `meta`
argument in `reactable()`.
`meta` should be a named list of values that can also be `JS()` expressions or functions.
Custom metadata can be accessed from JavaScript using the `state.meta` property, and updated
using `updateReactable()` in Shiny or [`Reactable.setMeta()`](./javascript-api.html#reactable-setmeta)
in the JavaScript API.
Use custom metadata to:
- Simplify JavaScript render functions that need access to data outside of the table
- Dynamically change how data is formatted without rerendering the table
- Share JavaScript code or data between different render functions
```{r}
library(htmltools)
data <- MASS::Cars93[1:6, c("Manufacturer", "Model", "Type", "Price", "MPG.city")]
exchange_rates <- list(
USD = 1,
CAD = 1.30,
JPY = 137.56
)
tbl <- reactable(
data,
columns = list(
Price = colDef(
cell = JS("function(cellInfo, state) {
const { currency, exchangeRates } = state.meta
const converted = cellInfo.value * exchangeRates[currency]
return converted.toLocaleString(undefined, { style: 'currency', currency: currency })
}")
)
),
meta = list(
currency = "USD",
exchangeRates = exchange_rates
),
elementId = "cars-currency-table"
)
browsable(
tagList(
tags$label(
"Currency",
tags$select(
onchange = "Reactable.setMeta('cars-currency-table', { currency: event.target.value })",
lapply(names(exchange_rates), tags$option)
)
),
tags$hr("aria-hidden" = "true"),
tbl
)
)
```
## Footers
You can add column footers using the `footer` argument in `colDef()`.
`footer` can either be custom content to render (e.g., a character string or HTML tag),
or a custom render function. See [Custom Rendering](custom-rendering.html) to learn
more about using custom render functions.
### R render function {#footers-r-render-function}
```{r, message=FALSE}
library(dplyr)
library(htmltools)
data <- MASS::Cars93[18:47, ] %>%
select(Manufacturer, Model, Type, Sales = Price)
reactable(
data,
defaultPageSize = 5,
columns = list(
Manufacturer = colDef(footer = "Total"),
Sales = colDef(footer = function(values) sprintf("$%.2f", sum(values)))
),
defaultColDef = colDef(footerStyle = list(fontWeight = "bold"))
)
```
### JavaScript render function {#footers-js-render-function}
::: {.callout}
This example requires reactable v0.3.0 or above.
:::
```{r}
reactable(
data,
searchable = TRUE,
defaultPageSize = 5,
minRows = 5,
columns = list(
Manufacturer = colDef(footer = "Total"),
Sales = colDef(
footer = JS("function(column, state) {
let total = 0
state.sortedData.forEach(function(row) {
total += row[column.id]
})
return total.toLocaleString('en-US', { style: 'currency', currency: 'USD' })
}")
)
),
defaultColDef = colDef(footerStyle = list(fontWeight = "bold"))
)
```
### Embedding HTML widgets {#embedding-html-widgets-footers}
```{r}
library(sparkline)
reactable(
iris[1:20, ],
defaultPageSize = 5,
bordered = TRUE,
defaultColDef = colDef(footer = function(values) {
if (!is.numeric(values)) return()
sparkline(values, type = "box", width = 100, height = 30)
})
)
```
## Expandable Row Details
::: {.callout}
This example requires reactable v0.3.0 or above.
:::
You can make rows expandable with additional content through `details`, which
takes an R or JavaScript render function. See [Custom Rendering](custom-rendering.html)
for details on how to use render functions.
```{r}
reactable(iris[1:5, ], details = function(index) {
htmltools::div(
"Details for row: ", index,
htmltools::tags$pre(paste(capture.output(iris[index, ]), collapse = "\n"))
)
})
```
The details column can be customized by providing a `colDef()` instead. This can
be used to add a column name, render HTML content, or change the column width:
```{r}
reactable(iris[1:5, ], details = colDef(
name = "More",
details = JS("function(rowInfo) {
return `Details for row: ${rowInfo.index}` +
`<pre>${JSON.stringify(rowInfo.values, null, 2)}</pre>`
}"),
html = TRUE,
width = 60
))
```
### Nested tables
With R render functions, you can render HTML tags, HTML widgets, and even nested tables:
```{r}
data <- unique(CO2[, c("Plant", "Type")])
reactable(data, details = function(index) {
plant_data <- CO2[CO2$Plant == data$Plant[index], ]
htmltools::div(style = "padding: 1rem",
reactable(plant_data, outlined = TRUE)
)
})
```
### Conditional row details
R render functions support conditional rendering. If a render function
returns `NULL`, the row won't be expandable:
```{r}
reactable(iris[1:5, ], details = function(index) {
if (index %in% c(3, 5)) {
reactable(data.frame(x = c(1, 2, 3), y = c("a", "b", "c")), fullWidth = FALSE)
}