| Type: | Package |
| Title: | A Wrapper of the JavaScript Library 'DataTables' |
| Version: | 0.34.0 |
| Description: | Data objects in R can be rendered as HTML tables using the JavaScript library 'DataTables' (typically via R Markdown or Shiny). The 'DataTables' library has been included in this R package. The package name 'DT' is an abbreviation of 'DataTables'. |
| License: | MIT + file LICENSE |
| URL: | https://github.com/rstudio/DT |
| BugReports: | https://github.com/rstudio/DT/issues |
| Imports: | crosstalk, htmltools (≥ 0.3.6), htmlwidgets (≥ 1.3),jquerylib, jsonlite (≥ 0.9.16), magrittr, promises |
| Suggests: | bslib, future, httpuv, knitr (≥ 1.8), rmarkdown, shiny (≥1.6), testit, tibble |
| VignetteBuilder: | knitr |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.2 |
| NeedsCompilation: | no |
| Packaged: | 2025-09-02 13:12:27 UTC; garrick |
| Author: | Yihui Xie [aut], Joe Cheng [aut], Xianying Tan [aut], Garrick Aden-Buie |
| Maintainer: | Garrick Aden-Buie <garrick@posit.co> |
| Repository: | CRAN |
| Date/Publication: | 2025-09-02 22:00:06 UTC |
Objects imported from other packages
Description
These objects are imported from other packages. Follow the links to their documentation.
- htmlwidgets
- magrittr
Coerce a character string to the same type as a target value
Description
Create a new value from a character string based on an old value, e.g., ifthe old value is an integer, callas.integer() to coerce the string toan integer.
Usage
coerceValue(val, old)Arguments
val | A character string. |
old | An old value, whose type is the target type of |
Details
This function only works with integer, double, date, time (POSIXlt orPOSIXct), and factor values. The date must be of the format\%Y-\%m-\%dT\%H:\%M:\%SZ. The factor value must be in the levels ofold, otherwise it will be coerced toNA.
Value
A value of the same data type asold if possible.
Examples
library(DT)coerceValue('100', 1L)coerceValue('1.23', 3.1416)coerceValue('2018-02-14', Sys.Date())coerceValue('2018-02-14T22:18:52Z', Sys.time())coerceValue('setosa', iris$Species)coerceValue('setosa2', iris$Species) # NAcoerceValue('FALSE', TRUE) # not supportedRegister a data object in a shiny session for DataTables
Description
This function stores a data object in a shiny session and returns a URL thatreturns JSON data based on DataTables Ajax requests. The URL can be used astheurl option inside theajax option of the table. It isbasically an implementation of server-side processing of DataTables in R.Filtering, sorting, and pagination are processed through R instead ofJavaScript (client-side processing).
Usage
dataTableAjax( session, data, rownames, filter = dataTablesFilter, outputId, future = FALSE)Arguments
session | the |
data | a data object (will be coerced to a data frame internally) |
rownames | see |
filter | (for expert use only) a function with two arguments |
outputId | the output ID of the table (the same ID passed to |
future | whether the server-side filter function should be executed as afuture or as a standard synchronous function. If true, the future will beevaluated according to the session'splan. |
Details
Normally you should not need to call this function directly. It is calledinternally when a table widget is rendered in a Shiny app to configure thetable optionajax automatically. If you are familiar withDataTables' server-side processing, and want to use a custom filterfunction, you may call this function to get an Ajax URL.
Value
A character string (an Ajax URL that can be queried by DataTables).
References
https://rstudio.github.io/DT/server.html
Examples
# !formatRDTApp = function(data, ..., options = list()) { library(shiny) library(DT) shinyApp( ui = fluidPage( title = 'Server-side processing of DataTables', fluidRow( DT::dataTableOutput('tbl') ) ), server = function(input, output, session) { options$serverSide = TRUE options$ajax = list(url = dataTableAjax(session, data, outputId = 'tbl')) # create a widget using an Ajax URL created above widget = datatable(data, ..., options = options) output$tbl = DT::renderDataTable(widget) } )}if (interactive()) DTApp(iris)if (interactive()) DTApp(iris, filter = 'top')Helper functions for using DT in Shiny
Description
These two functions are like mostfooOutput() andrenderFoo()functions in theshiny package. The former is used to create acontainer for table, and the latter is used in the server logic to render thetable.
Usage
dataTableOutput(outputId, width = "100%", height = "auto", fill = TRUE)DTOutput(outputId, width = "100%", height = "auto", fill = TRUE)renderDataTable( expr, server = TRUE, env = parent.frame(), quoted = FALSE, funcFilter = dataTablesFilter, future = FALSE, outputArgs = list(), ...)renderDT( expr, server = TRUE, env = parent.frame(), quoted = FALSE, funcFilter = dataTablesFilter, future = FALSE, outputArgs = list(), ...)Arguments
outputId | output variable to read the table from |
width | the width of the table container |
height | the height of the table container |
fill | passed to |
expr | an expression to create a table widget (normally via |
server | whether to use server-side processing. If |
env | The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. If |
quoted | If it is |
funcFilter | (for expert use only) passed to the |
future | whether the server-side filter function should be executed as afuture or as a standard synchronous function. If true, the future will beevaluated according to the session'splan. |
outputArgs | A list of arguments to be passed through to the implicitcall to |
... | ignored when |
References
https://rstudio.github.io/DT/shiny.html
Examples
# !formatRif (interactive()) { library(shiny) library(DT) shinyApp( ui = fluidPage(fluidRow(column(12, DTOutput('tbl')))), server = function(input, output) { output$tbl = renderDT( iris, options = list(lengthChange = FALSE) ) } )}Manipulate an existing DataTables instance in a Shiny app
Description
The functiondataTableProxy() creates a proxy object that can be usedto manipulate an existing DataTables instance in a Shiny app, e.g. selectrows/columns, or add rows.
Usage
dataTableProxy( outputId, session = shiny::getDefaultReactiveDomain(), deferUntilFlush = TRUE)selectRows(proxy, selected, ignore.selectable = FALSE)selectColumns(proxy, selected, ignore.selectable = FALSE)selectCells(proxy, selected, ignore.selectable = FALSE)addRow(proxy, data, resetPaging = TRUE)clearSearch(proxy)selectPage(proxy, page)updateCaption(proxy, caption)updateSearch(proxy, keywords = list(global = NULL, columns = NULL))showCols(proxy, show, reset = FALSE)hideCols(proxy, hide, reset = FALSE)colReorder(proxy, order, origOrder = FALSE)reloadData( proxy, resetPaging = TRUE, clearSelection = c("all", "none", "row", "column", "cell"))Arguments
outputId | the id of the table to be manipulated (the same id as the oneyou used in |
session | the Shiny session object (from the server function of theShiny app) |
deferUntilFlush | whether an action should be carried out right away, orshould be held until after the next time all of the outputs are updated |
proxy | a proxy object returned by |
selected | an integer vector of row/column indices, or a matrix of twocolumns (row and column indices, respectively) for cell indices; you mayuse |
ignore.selectable | when |
data | a single row of data to be added to the table; it can be a matrixor data frame of one row, or a vector or list of row data (in the lattercase, please be cautious about the row name: if your table contains rownames, here |
resetPaging | whether to reset the paging position |
page | a number indicating the page to select |
caption | a new table caption (see the |
keywords | a list of two components: |
show | a vector of column positions to show (the indexing starts at0, but if row.names are visible, they are the first column). |
reset | if |
hide | a vector of column positions to hide |
order | A numeric vector of column positions, starting from 0, and includingthe row.names as a column, if they are include. Must contain a valuefor all columns, regardless of whether they are visible or not. Also forcolumn reordering to work, the datatable must have extension 'ColReorder'set as well as option 'colReordoer' set to TRUE). |
origOrder | Whether column reordering should be relative to the originalorder (the default is to compare to current order) |
clearSelection | which existing selections to clear: it can be anycombinations of |
Note
addRow() only works for client-side tables. If you want to useit in a Shiny app, make sure to userenderDataTable(..., server = FALSE). Also note that the column filters (if used) of the table will notbe automatically updated when a new row is added, e.g., the range of theslider of a column will stay the same even if you have added a valueoutside the range of the original data column.
reloadData() only works for tables in the server-side processingmode, e.g. tables rendered withrenderDataTable(server = TRUE). Thedata to be reloaded (i.e. the one you pass todataTableAjax()) musthave exactly the same number of columns as the previous data object in thetable.
References
https://rstudio.github.io/DT/shiny.html
Create an HTML table widget using the DataTables library
Description
This function creates an HTML widget to display rectangular data (a matrix ordata frame) using the JavaScript library DataTables.
Usage
datatable( data, options = list(), class = "display", callback = JS("return table;"), rownames, colnames, container, caption = NULL, filter = c("none", "bottom", "top"), escape = TRUE, style = "auto", width = NULL, height = NULL, elementId = NULL, fillContainer = getOption("DT.fillContainer", NULL), autoHideNavigation = getOption("DT.autoHideNavigation", NULL), lazyRender = NULL, selection = c("multiple", "single", "none"), extensions = list(), plugins = NULL, editable = FALSE)Arguments
data | a data object (either a matrix or a data frame) |
options | a list of initialization options (seehttps://datatables.net/reference/option/); the character optionswrapped in |
class | the CSS class(es) of the table; seehttps://datatables.net/manual/styling/classes |
callback | the body of a JavaScript callback function with the argument |
rownames |
|
colnames | if missing, the column names of the data; otherwise it can bean unnamed character vector of names you want to show in the table headerinstead of the default data column names; alternatively, you can provide anamed numeric or character vector of the form |
container | a sketch of the HTML table to be filled with data cells; bydefault, it is generated from |
caption | the table caption; a character vector or a tag objectgenerated from |
filter | whether/where to use column filters; |
escape | whether to escape HTML entities in the table: |
style | either |
width,height | Width/Height in pixels (optional, defaults to automaticsizing) |
elementId | An id for the widget (a random string by default). |
fillContainer |
|
autoHideNavigation |
|
lazyRender |
|
selection | the row/column selection mode (single or multiple selectionor disable selection) when a table widget is rendered in a Shiny app;alternatively, you can use a list of the form |
extensions | a character vector of the names of the DataTablesextensions (https://datatables.net/extensions/index) |
plugins | a character vector of the names of DataTables plug-ins(https://rstudio.github.io/DT/plugins.html). Note that only thoseplugins supported by the |
editable |
|
Details
selection:
The argument could be a scalar string, which means the selection
mode, whose value could be one of'multiple'(the default),'single'and'none'(disable selection).When a list form is provided for this argument, only parts of the"full" list are allowed. The default values for non-matched elements are
list(mode = 'multiple', selected = NULL, target = 'row', selectable = NULL).targetmust be one of'row','column','row+column'and'cell'.selectedcould beNULLor "indices".selectablecould beNULL,TRUE,FALSEor "indices", whereNULLandTRUEmean all the table isselectable. WhenFALSE, it means users can't select the tableby the cursor (but they could still be able to select the table viadataTableProxy(), specifyingignore.selectable = TRUE).If "indices", they must be all positive or non-positive values. Allpositive "indices" mean only the specified ranges are selectable while allnon-positive "indices" mean those ranges arenot selectable.The "indices"' format is specified below.The "indices"' format of
selectedandselectable:whentargetis'row'or'column', it should be a plainnumeric vector; whentargetis'row+column', it should be alist, specifyingrowsandcolsrespectively, e.g.,list(rows = 1, cols = 2); whentargetis'cell',it should be a 2-colmatrix, where the two values of each rowstand for the row and column index.Note that DT has its own selection implementation and doesn'tuse the Select extension because the latter doesn't support theserver-side processing mode well. Please set this argument to
'none'if you really want to use the Select extension.
options$columnDefs:
columnDefsis an option that provided by the DataTables libraryitself, where the user can set various attributes for columns. It must beprovided as a list of list, where each sub-list must contain a vector named 'targets',specifying the applied columns, i.e.,list(list(..., targets = '_all'), list(..., targets = c(1, 2)))columnDefs$targetsis a vector and should be one of:0 or a positive integer: column index counting from the left.
A negative integer: column index counting from the right.
A string: the column name. Note, it must be the names of theoriginal data, not the ones that (could) be changed via param
colnames.The string "_all": all columns (i.e. assign a default).
When conflicts happen, e.g., a single column is defined for some propertytwice but with different values, the value that defined earlier takes the priority.For example,
list(list(visible=FALSE, target=1), list(visible=TRUE, target=1))results in a table whose first column isinvisible.Seehttps://datatables.net/reference/option/columnDefs for more.
filter:
filtercan be used to position and customize column filters.A scalar string value defines the position, and must be one of'none'(the default),'bottom'and'top'. A named list can be usedfor further control. In the named list form:$positionis a string as described above. It defaults to'none'.$clearis a logical value indicating if clearbuttons should appear in input boxes. It defaults toTRUE.$plainis a logical value indicating if plain stylingshould be used for input boxes instead of Bootstrap styling. Itdefaults toFALSE.$verticalis a logical value indicating if sliderwidgets should be oriented vertically rather than horizontally.It defaults toFALSE.$opacityis a numeric value between 0 and 1 used to setthe level of transparency of slider widgets. It defaults to1.$settingsis a named list used to directly pass configurationfor initializing filter widgets in JavaScript.The
$selectelement is passed to the select widget, and$slideris passed to the slider widget.Valid values depend on the settings accepted by the underlyingJavaScript libraries,SelectizeandnoUiSlider.Please note that the versions bundled with DT are currently quite old,so accepted settings may not match their most recent documentation.
These settings can override values set by DT, so specifyinga setting already in use may break something. Use with care.
Note
You are recommended to escape the table content for security reasons(e.g. XSS attacks) when using this function in Shiny or any other dynamicweb applications.
References
Seehttps://rstudio.github.io/DT/ for the fulldocumentation.
Examples
# !formatRlibrary(DT)# see the package vignette for examples and the link to websitevignette('DT', package = 'DT')# some boring edge cases for testing purposesm = matrix(nrow = 0, ncol = 5, dimnames = list(NULL, letters[1:5]))datatable(m) # zero rowsdatatable(as.data.frame(m))m = matrix(1, dimnames = list(NULL, 'a'))datatable(m) # one row and one columndatatable(as.data.frame(m))m = data.frame(a = 1, b = 2, c = 3)datatable(m)datatable(as.matrix(m))# datesdatatable(data.frame( date = seq(as.Date("2015-01-01"), by = "day", length.out = 5), x = 1:5))datatable(data.frame(x = Sys.Date()))datatable(data.frame(x = Sys.time()))Server-side searching
Description
doGlobalSearch() can be used to search a data frame given the searchstring typed by the user into the global search box of adatatable().doColumnSearch() does the same for a vectorgiven the search string typed into a column filter. These functions are usedinternally by the defaultfilter function passed todataTableAjax(), allowing you to replicate the search resultsthat server-side processing returns.
Usage
doColumnSearch(x, search_string, options = list())doGlobalSearch(data, search_string, options = list())Arguments
x | a vector, the type of which determines the expected |
search_string | a string that determines what to search for. The formatdepends on the type of input, matching what a user would type in theassociated filter control. |
options | a list of options used to control how searching charactervalues works. Supported options are |
data | a data frame |
Value
An integer vector of filtered row indices
See Also
The column filters section online for search string formats:https://rstudio.github.io/DT/
Accessing the search strings typed by a user in a Shiny app:https://rstudio.github.io/DT/shiny.html
Examples
doGlobalSearch(iris, 'versi')doGlobalSearch(iris, "v.r.i", options = list(regex = TRUE))doColumnSearch(iris$Species, '["versicolor"]')doColumnSearch(iris$Sepal.Length, '4 ... 5')Edit a data object using the information from the editor in a DataTable
Description
When editing cells in a DataTable in a Shiny app, we know the row/columnindices and values of the cells that were edited. With these information, wecan update the data object behind the DataTable accordingly.
Usage
editData(data, info, proxy = NULL, rownames = TRUE, resetPaging = FALSE, ...)Arguments
data | The original data object used in the DataTable. |
info | The information about the edited cells. It should be obtainedfrom |
proxy,resetPaging,... | (Optional) If |
rownames | Whether row names are displayed in the table. |
Value
The updated data object.
Note
For factor columns, new levels would be automatically added when necessaryto avoidNA coercing.
Format table columns
Description
Format numeric columns in a table as currency (formatCurrency()) orpercentages (formatPercentage()), or round numbers to a specifiednumber of decimal places (formatRound()), or a specified numberof significant figures (formatSignif()). The functionformatStyle() applies CSS styles to table cells by column.
Usage
formatCurrency( table, columns, currency = "$", interval = 3, mark = ",", digits = 2, dec.mark = getOption("OutDec"), before = TRUE, zero.print = NULL, rows = NULL)formatString(table, columns, prefix = "", suffix = "", rows = NULL)formatPercentage( table, columns, digits = 0, interval = 3, mark = ",", dec.mark = getOption("OutDec"), zero.print = NULL, rows = NULL)formatRound( table, columns, digits = 2, interval = 3, mark = ",", dec.mark = getOption("OutDec"), zero.print = NULL, rows = NULL)formatSignif( table, columns, digits = 2, interval = 3, mark = ",", dec.mark = getOption("OutDec"), zero.print = NULL, rows = NULL)formatDate(table, columns, method = "toDateString", params = NULL, rows = NULL)formatStyle( table, columns, valueColumns = columns, target = c("cell", "row"), fontWeight = NULL, color = NULL, backgroundColor = NULL, background = NULL, ...)Arguments
table | a table object created from |
columns | the indices of the columns to be formatted (can be character,numeric, logical, or a formula of the form |
currency | the currency symbol |
interval | put a marker after how many digits of the numbers |
mark | the marker after every |
digits | the number of decimal places to round to |
dec.mark | a character to indicate the decimal point |
before | whether to place the currency symbol before or after the values |
zero.print | a string to specify how zeros should be formatted.Useful for when many zero values exist. If |
rows | an integer vector (starting from 1) to specify the only rowsthat the style applies to.By default, it's |
prefix | string to put in front of the column values |
suffix | string to put after the column values |
method | the method(s) to convert a date to string in JavaScript; see |
params | a list parameters for the specific date conversion method,e.g., for the |
valueColumns | indices of the columns from which the cell values areobtained; this can be different with the |
target | the target to apply the CSS styles to (the current cell or thefull row) |
fontWeight | the font weight, e.g. |
color | the font color, e.g. |
backgroundColor | the background color of table cells |
background | the background of table cells |
... | other CSS properties, e.g. |
Note
The length of arguments other thantable should be 1 or the same asthe length ofcolumns.
References
Seehttps://rstudio.github.io/DT/functions.html for detaileddocumentation and examples.
Examples
# !formatRlibrary(DT)m = cbind(matrix(rnorm(120, 1e5, 1e6), 40), runif(40), rnorm(40, 100))colnames(m) = head(LETTERS, ncol(m))m# format the columns A and C as currency, and D as percentagesdatatable(m) %>% formatCurrency(c('A', 'C')) %>% formatPercentage('D', 2)# the first two columns are Euro currency, and round column E to 3 decimal placesdatatable(m) %>% formatCurrency(1:2, '\U20AC') %>% formatRound('E', 3)# render vapor pressure with only two significant figures.datatable(pressure) %>% formatSignif('pressure',2)# apply CSS styles to columnsdatatable(iris) %>% formatStyle('Sepal.Length', fontWeight = styleInterval(5, c('bold', 'weight'))) %>% formatStyle('Sepal.Width', color = styleInterval(3.4, c('red', 'white')), backgroundColor = styleInterval(3.4, c('yellow', 'gray')) )Replace data in an existing table
Description
Replace the data object of a table output and avoid regenerating the fulltable, in which case the state of the current table will be preserved(sorting, filtering, and pagination) and applied to the table with new data.
Usage
replaceData(proxy, data, ..., resetPaging = TRUE, clearSelection = "all")updateFilters(proxy, data)Arguments
proxy | a proxy object created by |
data | the new data object to be loaded in the table |
... | other arguments to be passed to |
resetPaging,clearSelection | passed to |
Note
When you replace the data in an existing table, please make sure thenew data has the same number of columns as the current data. When you haveenabled column filters, you should also make sure the attributes of everycolumn remain the same, e.g. factor columns should have the same or fewerlevels, and numeric columns should have the same or smaller range,otherwise the filters may never be able to reach certain rows in the data,unless you explicitly update the filters withupdateFilters().
If theColReorder extension is used, the newdata must havecolumn names that match the original data column names exactly.
Conditional CSS styles
Description
A few helper functions for theformatStyle() function tocalculate CSS styles for table cells based on the cell values. Under thehood, they just generate JavaScript and CSS code from the values specified inR.
Usage
styleInterval(cuts, values)styleEqual(levels, values, default = NULL)styleValue()styleColorBar(data, color, angle = 90)styleRow(rows, values, default = NULL)Arguments
cuts | a vector of cut points (sorted increasingly) |
values | a vector of CSS values |
levels | a character vector of data values to be mapped (one-to-one) toCSS values |
default | a string or |
data | a numeric vector whose range will be used for scaling thetable data from 0-100 before being represented as color bars. A vectorof length 2 is acceptable here for specifying a range possibly wider ornarrower than the range of the table data itself. |
color | the color of the bars |
angle | a number of degrees representing the direction to fill thegradient relative to a horizontal line and the gradient line, goingcounter-clockwise. For example, 90 fills right to left and -90 fillsleft to right. |
rows | the Row Indexes (starting from 1) that applies the CSS style. It couldbe an integer vector or a list of integer vectors, whose length must be equal tothe length of |
Details
The functionstyleInterval() maps intervals to CSS values. Itsargumentvalues must be of lengthn + 1 wheren = length(cuts). The right-closed interval ‘(cuts[i - 1], cuts[i]]’ ismapped to ‘values[i]’ for ‘i = 2, 3, ..., n’; ‘values[1]’ isfor the interval ‘(-Inf, cuts[1]]’, and ‘values[n + 1]’ is for‘(cuts[n], +Inf)’. You can think of the order ofcuts andvalues using this diagram: ‘-Inf -> values[1] -> cuts[1] ->values[2] -> cuts[2] -> ... -> values[n] -> cuts[n] -> values[n + 1] ->+Inf’.
The functionstyleEqual() maps data values to CSS values in theone-to-one manner, i.e.values[i] is used when the table cell value islevels[i].
The functionstyleColorBar() can be used to draw background color barsbehind table cells in a column, and the width of bars is proportional to thecolumn values.
The functionstyleValue() uses the column value as the CSS values.
The functionstyleRow() applies the CSS values based on Row Indexes.This only works expected in the client-side processing mode, i.e.,server = FALSE.
Generate a table header or footer from column names
Description
Convenience functions to generate a table header (‘<thead></thead>’) orfooter (‘<tfoot></tfoot>’) given the column names. They are basicallywrappers ofhtmltools::tags$th applied to the column names.
Usage
tableHeader(names, escape = TRUE)tableFooter(names, escape = TRUE)Arguments
names | a character vector of the column names of the table (if it is anobject with column names, its column names will be used instead) |
escape | whether to escape the names (see |
Value
A tag object generated byhtmltools::tags.
Examples
library(DT)tableHeader(iris) # or equivalently,tableHeader(colnames(iris))tableFooter(iris) # footerlibrary(htmltools)tags$table(tableHeader(iris), tableFooter(iris))