Movatterモバイル変換


[0]ホーム

URL:


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-BuieORCID iD [aut, cre], JJ Allaire [ctb], Maximilian Girlich [ctb], Greg Freedman Ellis [ctb], Johannes Rauh [ctb], SpryMedia Limited [ctb, cph] (DataTables in htmlwidgets/lib), Brian Reavis [ctb, cph] (selectize.js in htmlwidgets/lib), Leon Gersen [ctb, cph] (noUiSlider in htmlwidgets/lib), Bartek Szopka [ctb, cph] (jquery.highlight.js in htmlwidgets/lib), Alex Pickering [ctb], William Holmes [ctb], Mikko Marttila [ctb], Andres Quintero [ctb], Stéphane Laurent [ctb], Posit Software, PBC [cph, fnd]
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

JS,saveWidget

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 ofval.

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 supported

Register 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

thesession object in the shiny server function(⁠function(input, output, session)⁠)

data

a data object (will be coerced to a data frame internally)

rownames

seedatatable(); it must be consistent withwhat you use indatatable(), e.g. if the widget is generated bydatatable(rownames = FALSE), you must also usedataTableAjax(rownames = FALSE) here

filter

(for expert use only) a function with two argumentsdataandparams (Ajax parameters, a list of the formlist(search = list(value = 'FOO', regex = 'false'), length = 10, ...)) that return thefiltered table result according to the DataTables Ajax request

outputId

the output ID of the table (the same ID passed todataTableOutput(); if missing, an attempt to infer it fromsession is made. If it can't be inferred, a random id isgenerated.)

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 tohtmlwidgets::shinyWidgetOutput(), seethere for explanation (requireshtmlwidgets > v1.5.4).

expr

an expression to create a table widget (normally viadatatable()), or a data object to be passed todatatable() to create a table widget

server

whether to use server-side processing. IfTRUE, then thedata is kept on the server and the browser requests a page at a time; ifFALSE, then the entire data frame is sent to the browser at once.Highly recommended for medium to large data frames, which can causebrowsers to slow down or crash. Note that if you want to userenderDataTable withshiny::bindCache(), this must beFALSE.

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifexpr is a quosure andquoted isTRUE, thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofexpr will be used whenexpr is evaluated. Ifexpr is aquosure and you would like to use its expression as a value forexpr, then you must setquoted toTRUE.

funcFilter

(for expert use only) passed to thefilter argumentofdataTableAjax()

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 todataTableOutput() whenrenderDataTable() is used in an interactive R Markdowndocument.

...

ignored whenexpr returns a table widget, and passed asadditional arguments todatatable() whenexpr returnsa data object

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 indataTableOutput())

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 bydataTableProxy()

selected

an integer vector of row/column indices, or a matrix of twocolumns (row and column indices, respectively) for cell indices; you mayuseNULL to clear existing selections

ignore.selectable

whenFALSE (the default), the "non-selectable"range specified byselection = list(selectable= ) is respected, i.e.,you can't select "non-selectable" range. Otherwise, it is ignored.

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, heredata must also contain the row name as the firstelement)

resetPaging

whether to reset the paging position

page

a number indicating the page to select

caption

a new table caption (see thecaption argument ofdatatable())

keywords

a list of two components:global is the global searchkeyword of a single character string (ignored ifNULL);columns is a character vector of the search keywords for all columns(when the table has one column for the row names, this vector of keywordsshould contain one keyword for the row names as well)

show

a vector of column positions to show (the indexing starts at0, but if row.names are visible, they are the first column).

reset

ifTRUE, will only show/hide the columns indicated.

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 ofrow,column, andcell, orallfor all three, ornone to keep current selections (by default, allselections are cleared after the data is reloaded)

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 inhtmlwidgets::JS() will be treated as literalJavaScript code instead of normal character strings; you can also setoptions globally via⁠[options](DT.options = list(...))⁠, andglobal options will be merged into thisoptions argument if set

class

the CSS class(es) of the table; seehttps://datatables.net/manual/styling/classes

callback

the body of a JavaScript callback function with the argumenttable to be applied to the DataTables instance (i.e.table)

rownames

TRUE (show row names) orFALSE (hide row names)or a character vector of row names; by default, the row names are displayedin the first column of the table if exist (notNULL)

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⁠'newName1' = i1, 'newName2' = i2⁠ orc('newName1' = 'oldName1', 'newName2' = 'oldName2', ...), wherenewName is the new name you want to show inthe table, andi oroldName is the index of the currentcolumn name

container

a sketch of the HTML table to be filled with data cells; bydefault, it is generated fromhtmltools::tags$table() with a tableheader consisting of the column names of the data

caption

the table caption; a character vector or a tag objectgenerated fromhtmltools::tags$caption()

filter

whether/where to use column filters;none: no filters;bottom/top: put column filters at the bottom/top of the table; rangesliders are used to filter numeric/date/time columns, select lists are usedfor factor columns, and text input boxes are used for character columns; ifyou want more control over the styles of filters, you can provide a namedlist to this argument; see Details for more

escape

whether to escape HTML entities in the table:TRUE meansto escape the whole table, andFALSE means not to escape it;alternatively, you can specify numeric column indices or column names toindicate which columns to escape, e.g.1:5 (the first 5 columns),c(1, 3, 4), orc(-1, -3) (all columns except the first andthird), orc('Species', 'Sepal.Length'); since the row names takethe first column to display, you should add the numeric column indices byone when usingrownames

style

either'auto','default','bootstrap', or'bootstrap4'. If'auto', and abslib theme iscurrently active, then bootstrap styling is used in a way that "just works"for the active theme. Otherwise,DataTables'default' styling is used. If set explicitly to'bootstrap'or'bootstrap4', one must take care to ensure Bootstrap's HTMLdependencies (as well as Bootswatch themes, if desired) are included on thepage. Note, when set explicitly, it's the user's responsibility to ensurethat only one uniquestyle value is used on the same page, if multipleDT tables exist, as different styling resources may conflict with each other.

width,height

Width/Height in pixels (optional, defaults to automaticsizing)

elementId

An id for the widget (a random string by default).

fillContainer

TRUE to configure the table to automatically fillit's containing element. If the table can't fit fully into it's containerthen vertical and/or horizontal scrolling of the table cells will occur.

autoHideNavigation

TRUE to automatically hide navigational UI(only display the table body) when the number of total records is lessthan the page size. Note, it only works on the client-side processing modeand thepageLength option should be provided explicitly.

lazyRender

FALSE to render the table immediately on page load,otherwise delay rendering until the table becomes visible.

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 formlist(mode = 'multiple', selected = c(1, 3, 8), target = 'row', selectable = c(-2, -3)) topre-select rows and control the selectable range; the elementtarget in the list can be'column' to enable columnselection, or'row+column' to make it possible to select both rowsand columns (click on the footer to select columns), or'cell' toselect cells. See details section for more info.

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 theDT package can be used here. You can seethe available plugins by callingDT:::available_plugins()

editable

FALSE to disable the table editor, orTRUE (or"cell") to enable editing a single cell. Alternatively, you can setit to"row" to be able to edit a row, or"column" to edit acolumn, or"all" to edit all cells on the current page of the table.In all modes, start editing by doubleclicking on a cell. This argument canalso be a list of the formlist(target = TARGET, disable = list(columns = INDICES)), whereTARGET can be"cell","row","column", or"all", andINDICES is aninteger vector of column indices. Use the list form if you want to disableediting certain columns. You can also restrict the editing to accept onlynumbers by setting this argument to a list of the formlist(target = TARGET, numeric = INDICES) whereINDICES can be the vector of theindices of the columns for which you want to restrict the editing tonumbers or"all" to restrict the editing to numbers for all columns.If you don't setnumeric, then the editing is restricted to numbersfor all numeric columns; setnumeric = "none" to disable thisbehavior. It is also possible to edit the cells in text areas, which areuseful for large contents. For that, set theeditable argument to alist of the formlist(target = TARGET, area = INDICES) whereINDICES can be the vector of the indices of the columns for whichyou want the text areas, or"all" if you want the text areas forall columns. Of course, you can request the numeric editing for somecolumns and the text areas for some other columns by settingeditable to a list of the formlist(target = TARGET, numeric = INDICES1, area = INDICES2). Finally, you can edit date cells with acalendar withlist(target = TARGET, date = INDICES); the targetcolumns must have theDate type. If you don't setdate intheeditable list, the editing with the calendar is automaticallyset for allDate columns.

Details

selection:

  1. The argument could be a scalar string, which means the selectionmode, whose value could be one of'multiple' (the default),'single' and'none' (disable selection).

  2. When a list form is provided for this argument, only parts of the"full" list are allowed. The default values for non-matched elements arelist(mode = 'multiple', selected = NULL, target = 'row', selectable = NULL).

  3. target must be one of'row','column','row+column' and'cell'.

  4. selected could beNULL or "indices".

  5. selectable could beNULL,TRUE,FALSEor "indices", whereNULL andTRUE mean 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.

  6. The "indices"' format ofselected andselectable:whentarget is'row' or'column', it should be a plainnumeric vector; whentarget is'row+column', it should be alist, specifyingrows andcols respectively, e.g.,list(rows = 1, cols = 2); whentarget is'cell',it should be a 2-colmatrix, where the two values of each rowstand for the row and column index.

  7. 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:

  1. columnDefs is 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)))

  2. columnDefs$targets is 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 paramcolnames.

    • The string "_all": all columns (i.e. assign a default).

  3. 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.

  4. Seehttps://datatables.net/reference/option/columnDefs for more.

filter:

  1. filter can 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:

  2. ⁠$position⁠ is a string as described above. It defaults to'none'.

  3. ⁠$clear⁠ is a logical value indicating if clearbuttons should appear in input boxes. It defaults toTRUE.

  4. ⁠$plain⁠ is a logical value indicating if plain stylingshould be used for input boxes instead of Bootstrap styling. Itdefaults toFALSE.

  5. ⁠$vertical⁠ is a logical value indicating if sliderwidgets should be oriented vertically rather than horizontally.It defaults toFALSE.

  6. ⁠$opacity⁠ is a numeric value between 0 and 1 used to setthe level of transparency of slider widgets. It defaults to1.

  7. ⁠$settings⁠ is a named list used to directly pass configurationfor initializing filter widgets in JavaScript.

    • The⁠$select⁠ element is passed to the select widget, and⁠$slider⁠ is 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 expectedsearch_string format

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 areregex,caseInsensitiveand (for global search)smart.

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 obtainedfrominput$tableId_cell_edit from Shiny, and is a data framecontaining columnsrow,col, andvalue.

proxy,resetPaging,...

(Optional) Ifproxy is provided, it mustbe either a character string of the output ID of the table or a proxyobject created fromdataTableProxy(), and the rest ofarguments are passed toreplaceData() to update the data in aDataTable instance in a Shiny app.

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 fromdatatable()

columns

the indices of the columns to be formatted (can be character,numeric, logical, or a formula of the form~ V1 + V2, which isequivalent toc('V1', 'V2'))

currency

the currency symbol

interval

put a marker after how many digits of the numbers

mark

the marker after everyinterval decimals in the numbers

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. IfNULL, keeps zero as it is.

rows

an integer vector (starting from 1) to specify the only rowsthat the style applies to.By default, it'sNULL, meaning all rows should be formatted. Note,formatStyle() doesn't support this argument and you should usestyleRow() instead. In addition, this only works expected in theclient-side processing mode, i.e.,server = FALSE.

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; seeDT:::DateMethods for a list of possible methods, andhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Datefor a full reference

params

a list parameters for the specific date conversion method,e.g., for thetoLocaleDateString() method, your browser may supportparams = list('ko-KR', list(year = 'numeric', month = 'long', day = 'numeric'))

valueColumns

indices of the columns from which the cell values areobtained; this can be different with thecolumns argument, e.g. youmay style one column based on the values of a different column

target

the target to apply the CSS styles to (the current cell or thefull row)

fontWeight

the font weight, e.g.'bold' and'normal'

color

the font color, e.g.'red' and'#ee00aa'

backgroundColor

the background color of table cells

background

the background of table cells

...

other CSS properties, e.g.'border','font-size','text-align', and so on; if you want to condition CSS styles on thecell values, you may use the helper functions such asstyleInterval(); note the actual CSS property names aredash-separated, but you can use camelCase names in this function (otherwiseyou will have to use backticks to quote the names, e.g. “font-size⁠ = '12px'⁠), and this function will automatically convert camelCase names todash-separated names (e.g. ''fontWeight'' will be converted to''font-weight'' internally)

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 bydataTableProxy()

data

the new data object to be loaded in the table

...

other arguments to be passed todataTableAjax()

resetPaging,clearSelection

passed toreloadData()

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 orNULL used as the the default CSS valuefor values other than levels. IfNULL, the CSS value of non-matchedcells will be left unchanged.

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 ofvalues, whenvalues is not a scalar.

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 (seedatatable())

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))

[8]ページ先頭

©2009-2025 Movatter.jp