GithubHelp home page GithubHelp logo

rstudio / dt Goto Github PK

View Code? Open in Web Editor NEW
584.0 77.0 181.0 8.59 MB

R Interface to the jQuery Plug-in DataTables

Home Page: https://rstudio.github.io/DT/

License: Other

R 5.50% CSS 0.57% JavaScript 93.93%
r datatables javascript r-package htmlwidgets shiny

dt's Introduction

An R interface to the DataTables library

R-CMD-check Codecov test coverage Downloads from the RStudio CRAN mirror

This package provides a function datatable() to display R data via the DataTables library (N.B. not to be confused with the data.table package).

Installation

You may install the stable version from CRAN, or the development version using remotes:

# install from CRAN
install.packages('DT')

# or the development version if necessary
# install.packages("pak")
pak::pak('rstudio/DT')

# then try DT::datatable(iris) as a hello world example

See the full documentation at https://rstudio.github.io/DT/. Please use Github issues only if you want to file bug reports or feature requests, and you are expected to ask questions on StackOverflow with at least the tags r and dt.

Please note that due to limited resources, this package is currently in the maintenance-only mode. The only priority is to fix important bugs. We welcome you to submit pull requests to implement new features or fix bugs, but cannot guarantee these pull requests will be reviewed or merged (we will try our best). Thanks for your understanding! BTW, you may also consider other packages for making tables, although DT has a few unique features that are unlikely to be available in other packages.

dt's People

Contributors

carlganz avatar cderv avatar cpsievert avatar ecortens avatar fbreitwieser avatar gadenbuie avatar gergness avatar gsmolinski avatar guoci avatar hafen avatar haozhu233 avatar hdrab127 avatar hedsnz avatar jarauh avatar jcheng5 avatar jjallaire avatar lrasmus avatar mgirlich avatar mikmart avatar mosk915 avatar mtmorgan avatar pedropark99 avatar rfhb avatar shrektan avatar stla avatar thomasrockhu-codecov avatar tyler-richardett avatar wch avatar wholmes105 avatar yihui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dt's Issues

DT with knitr and slidify

Hi @yihui. I have some problems with knitr and slidify with DT. I don't have any problem with rmarkdown package. However I would like to use DT with slidify.

I tried with results='asis' but it doesn't work because this problem is related to the HTML output.
image

Thanks in advance and happy new yeaR!

My session Info

R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=Spanish_Peru.1252 LC_CTYPE=Spanish_Peru.1252 LC_MONETARY=Spanish_Peru.1252
[4] LC_NUMERIC=C LC_TIME=Spanish_Peru.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] DT_0.0.6 slidifyLibraries_0.3.1 slidify_0.4.5

loaded via a namespace (and not attached):
[1] digest_0.6.4 evaluate_0.5.5 formatR_1.0 htmltools_0.2.7 htmlwidgets_0.3.2
[6] knitr_1.8 magrittr_1.0.1 markdown_0.7.4 RJSONIO_1.3-0 stringr_0.6.2
[11] tools_3.1.1 whisker_0.3-2 yaml_2.1.13

Column filter css affected when switching to tab/page with shiny slider

In style.css I have:

table.dataTable tfoot td, table.dataTable thead td {
padding-top: 0px;
padding-bottom: 0px;
padding-left: 0px;
padding-right: 0px;
}

In Data > View this looks fine. Go to Base > Single mean (which has a filter) and then back to Data > View and you will see the css has been changed. This happens for any page with a slider (e.g, all tools in Base except Cross-tabs, Regression (OLS and GLM, but not Correlation which doesn't have a slider). To test this some more I added a slider to the Data > Visualize tab and the same effect occurred. Switching back and forth changes the CSS.

Note that this effect also occurs when I comment out the CSS listed above. In that case the default CSS for the column headers/footers is still changed when switching back and forth to pages with shiny sliders.

See for link below for example:

https://vnijs.shinyapps.io/quant

All package versions used are at: https://github.com/vnijs/radiant_miniCRAN

horizontal scroll bar with shinydashboard

Hi Yihui,

It seems there is a problem when a shiny app displays a dataframe with many columns with shiny dashboard :

library(shiny)
library(shinydashboard)
library(DT)

ui = dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(DT::dataTableOutput('tbl'))
)
server = function(input, output, session) {
  output$tbl = DT::renderDataTable({
    DT::datatable(volcano, filter = 'top', options = list(autoWidth = T))
  })
}
runApp(list(ui=ui,server=server))

I don't have any horizontal scroll bar at the bottom.

Matthieu

TableTools windows don't show up on shinyapps.i.o

I have an app with multiple tables. When I run the app from R studio it works fine. When I deploy the app to shinyapps.i.o the windows for Copy, CSV, EXCEL... no longer come up. Copy is still working, I can paste from the clipboard, but the windows don't come up. I can't save a CSV because the window won't come up

I thought it might have something to do with multiple tables but the same path for
list(sSwfPath = copySWF('www')). I tried creating separate directories and folders for each table.

With a directory within the 'www' folder I get the same results from R studio when I deploy to shinyapps.i.o.

No TableTools windows from Rstudio or shinyapps.i.o (I checked to make sure I created the inventory directory):

EditInventoryDT<-datatable(df, rownames=FALSE,extensions = list``(Scroller=NULL,TableTools=NULL,FixedColumns=list(leftColumns=1)),
options = list(
dom = 'T<"clear">lfrtip',
autoWidth=TRUE,
columnDefs = list(list(width = '30%', targets = list(6,7))),
deferRender=TRUE,
scrollX=TRUE,scrollY=400,
scrollCollapse=TRUE,
pageLength = 100, lengthMenu = c(10,50,100,200),
tableTools=list(sSwfPath = copySWF('www/inventory'))
))

This works from Rstudio, but not from shinyapps.i.o.:

EditInventoryDT<-datatable(df, rownames=FALSE,extensions = list``(Scroller=NULL,TableTools=NULL,FixedColumns=list(leftColumns=1)),
options = list(
dom = 'T<"clear">lfrtip',
autoWidth=TRUE,
columnDefs = list(list(width = '30%', targets = list(6,7))),
deferRender=TRUE,
scrollX=TRUE,scrollY=400,
scrollCollapse=TRUE,
pageLength = 100, lengthMenu = c(10,50,100,200),
tableTools=list(sSwfPath = copySWF('www'))
))

DT's on shinyapps.i.o not working

My DT's are fine when I work from Rstudio, but when I deploy the app, The table doesn't show up. Oddly it works for one set of data and not another. (I know that sounds bad for me on my end)

But, I think this is related to a recent issue with the TableTools buttons, as it has the same symptoms - It works fine from Rstudio, but not on shinnyapps.i.o. And it is giving me an error I have not seen before, I am wondering if this is related to yesterday's bug fix.

"Error input string 56 is invalid in this locale"

Yihui - I will send you a personal note to a reproducible example.

Here is my code, this works fine from Rstudio, but not on the web.

    EditInventoryDT<-datatable(df, rownames=FALSE,extensions = list(Scroller=NULL,TableTools=NULL,FixedColumns=list(leftColumns=3)), 
                       options = list(
                         dom = 'T<"clear">lfrtip',
                         autoWidth=TRUE,
                         columnDefs = list(list(width ='30%', targets = list(6,7))),
                         deferRender=TRUE,
                         scrollX=TRUE,scrollY=500,
                         scrollCollapse=TRUE,
                         pageLength = 100, lengthMenu = c(10,50,100,200),
                         tableTools=list(sSwfPath = copySWF('www'))
                       ))

I also tried stripping down the options as shown below and this also has the same issues, works fine from Rstudio, but then not when I deploy the app (I though it might be somehow tied to recent TableTools work, so I took that out. Unfortunately no luck with this either

   EditInventoryDT<-datatable(df, rownames=FALSE,extensions = list(Scroller=NULL,FixedColumns=list(leftColumns=3)), 
                               options = list(
                                 #dom = 'T<"clear">lfrtip',
                                 dom = 't',
                                 autoWidth=TRUE,
                                 columnDefs = list(list(width ='30%', targets = list(6,7))),
                                 #deferRender=TRUE,
                                 scrollX=TRUE,scrollY=500,
                                 scrollCollapse=TRUE,
                                 pageLength = 100, lengthMenu = c(10,50,100,200)

                               ))

Install in docker rstudio server ?

I am not able to install DT in my docker [rocker/hadleyverse] image

> devtools::install_github('rstudio/DT')
Downloading github repo rstudio/DT@master
Error in download(dest, src, auth) : client error: (403) Forbidden

Any ideas about how to solve this problem?

Thanks!

Filter + custom container?

Is it possible to have a filter and a custom container using DT?

The following code is not working

library(DT)
# a custom table container
sketch = htmltools::withTags(table(
  class = 'display',
  thead(
    tr(
      th(rowspan = 2, 'Current Industry'),
      th(colspan = 3, 'Share of Workers'),
      th(colspan = 3, 'Share of Workers w/a Pro Cert (Q1)'),
      th(colspan = 3, 'Share of Workers w. Certificate (Q10)')
    ),
    tr(
      lapply(rep(c('Overall', 'Male', 'Female'), 3), th)
    )
  )
))
table1 = structure(c(4570, 8980, 6e-04, 0.0067, 0.8455, 0.1154, 0.1545, 
                     0.8846, 0.6998, 0.6348, 0.9416, 0.1349, 0.0584, 0.8651, 0.1742, 
                     0.2279, 1, 0.1568, 0, 0.8432), .Dim = c(2L, 10L), .Dimnames = list(
                       NULL, c("industry", "Overall1", "Male1", "Female1", "Overall2", 
                               "Male2", "Female2", "Overall3", "Male3", "Female3")))

datatable(table1, filter = 'top', container = sketch, caption = 'Table 1: Certification by industry',
          rownames = FALSE, options = list(pageLength = 15, lengthMenu = c(5, 10, 15, 50, 100))) %>%
  formatPercentage(2:10, 2)

Thanks!

custom table container?

I'm trying to use DataTables with R to generate an html table with a custom header. The header is not working as expected and the problem is very hard to repoduce. If I use dput to create my original object, the problem goes away...

This is how the table looks like:

enter image description here

As you can see the is a big space between Male and Female.

This is the code I'm running to create that table:

library(DT)

table1 <- readRDS(file = "./table.RDS")

# a custom table container
sketch = htmltools::withTags(table(
  class = 'display',
  thead(
    tr(
      th(rowspan = 2, 'Current Industry'),
      th(colspan = 3, 'Share of Workers'),
      th(colspan = 3, 'Share of Workers w/a Pro Cert (Q1)'),
      th(colspan = 3, 'Share of Workers w. Certificate (Q10)')
    ),
    tr(
      lapply(rep(c('Overall', 'Male', 'Female'), 3), th)
    )
  )
))

datatable(table1, container = sketch, caption = 'Table 1: Certification by industry',
          rownames = FALSE, options = list(pageLength = 15, lengthMenu = c(5, 10, 15, 50, 100))) %>%
  formatPercentage(2:10, 2)

This is a link to the data. The most annoying part is that the problem goes away if you use dput. That is:

table1 = structure(c(4570, 8980, 6e-04, 0.0067, 0.8455, 0.1154, 0.1545, 
0.8846, 0.6998, 0.6348, 0.9416, 0.1349, 0.0584, 0.8651, 0.1742, 
0.2279, 1, 0.1568, 0, 0.8432), .Dim = c(2L, 10L), .Dimnames = list(
    NULL, c("industry", "Overall1", "Male1", "Female1", "Overall2", 
    "Male2", "Female2", "Overall3", "Male3", "Female3")))

Any idea of why and how to fix this?

Thanks!

(enhancement) add checkbox to DT

@yihui It would be great to add checkbox on datatables / DT.
I've toyed a bit with this on earlier version and I found the following issues, that would require addressing in view of a larger more general adoption:

  • In the old datatables a "ticked" check box didn't survive pagination or sorting: at the very least it is important to have means to "save" server-side the info on which checkboxes have been selected before allowing paging or sorting (or allow checkboxes only when 'Scroller" is T & pagination is F.
  • As a way to manage the info from the boxes this should be implemented alongside the indexing strategy (as discussed here)
  • Full abillity to set a checkbox on or off from server-side
  • In an ideal world checkboxes on columns as well as on rows (through lists?)

DT_RowId, or an approach to row selection info

To be able to get the indices of selected rows, we need the id's of rows stored somewhere. DataTables accepts a field DT_RowId returned from the server data (http://www.datatables.net/examples/server_side/ids.html), but then we will have to use objects instead of arrays as the data source, which will be (slightly) more complicated. See https://groups.google.com/forum/#!topic/shiny-discuss/_1h6eStpr2U

An alternative (and IMO simpler) approach is to add the row id's as a column in the table, but do not display this column: http://datatables.net/reference/option/columns.visible Then users only need the data from this column to retrieve the selected rows from R.

using checkboxes: how to avoid a race?

If you click very fast on one checkbox, the datatable and the resulting slider enter in an endless loop. It happens also in my app.
I have built the code below (apologies for the length) to reproduce it.

What could I do to avoid this??

library(DT)
library(shiny)

quantity <- id <- 1:nrow(iris)
label <- paste0("lab","-",quantity)
iris_ <- cbind(id=id,quantity=quantity,label=label,iris ,stringsAsFactors = FALSE)
cols <- colnames(iris_)

ui <- fluidPage(
    fluidRow(
        column(8,DT::dataTableOutput('demTb')),
        column(3,uiOutput("demSli"))
        )
    )

server <- function(session, input, output) {


output$demSli <- renderUI({

if(is.null(input$demTb_selected) ) return()

isolate({
index <- input$demTb_selected

labs <- iris_$label[index] 
pages <- "test"
iter <- length(labs)
buttn <- 1
valLabs <- sapply(1:iter, function(i) {
if(is.null(input[[paste0(pages,"d",labs[i],buttn)]] )) {
          0
} else {  as.numeric(input[[paste0(pages,"d",labs[i],buttn)]])  }
}) 
#
toRender <- lapply(1:iter, function(i) {
  sliderInput(inputId = paste0(pages,"d",labs[i],buttn),
              label =  h6(paste0(labs[i],"")),
              min = -100,
              max = 100,
              step = 1,
              value = valLabs[i],
              post="%",
              ticks = FALSE, animate = FALSE)
              })
})
      return(toRender)

})
#
rds <- reactive({
if( is.null(input$demTb_selected) ) return(iris_)
index <- input$demTb_selected
isolate({
labs <- iris_$label[index] 
pages <- "test"
iter <- length(labs)
buttn <- 1
}) # end isolate
valLabs <- sapply(1:iter, function(i) {
    if(is.null(input[[paste0(pages,"d",labs[i],buttn)]] )) {
      0
    } else {  
      as.numeric(input[[paste0(pages,"d",labs[i],buttn)]])/100  
    }
  })

  df_ <- data.frame(label=labs, multi=valLabs, stringsAsFactors = FALSE)
  df_ <- merge(iris_,df_,by="label", all.x=T)
  ifelse( is.na( df_$multi), df_$quantity, df_$quantity*(1 + df_$multi) )
  df_$multi <- NULL
  return(df_)
  }) 


output$demTb = DT::renderDataTable({


if(is.null(rds() )) return()
df_ <- rds() 
df_ <- df_[cols]
df_ <- df_[with(df_,order(as.numeric(id))),]

DT::datatable(df_,extensions= 'Scroller', rownames = checkboxRows(df_, input$demTb_selected),
      escape = -1,
      options=list(
      # deferRender = TRUE,
      dom = 'frtiS',
      scrollX = TRUE,
      scrollY = 300,
      scrollCollapse = TRUE,
      searching=F
      ))

    })

}


shinyApp(ui, server)

Table Class "Compact" Has Poor Column Label Layout

If applying the Table CSS Class "compact" the column order arrows appear underneath the column labels.

Below are two images to demonstrate this. The first image is "normal" table layout. The second image uses class = 'compact'

tablelayoutnormal
tablelayoutcompact

Code to produce the table with layout error.

library("shiny")
library("shinydashboard")
library("datasets")
library("DT")

header <- dashboardHeader()

sidebar <- dashboardSidebar()

body <- dashboardBody(
  DT::dataTableOutput("mtcarsTable")
)

shinyApp(
  ui = dashboardPage(header, sidebar, body),
  server = function(input, output) {

    output$mtcarsTable <- renderDataTable({
      DT::datatable(datasets::mtcars, 
                    class = 'compact',
                    options = list(rowCallback = JS('
                          function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                                                    // Bold and green cells for conditions
                                                    if (parseFloat(aData[3]) >= 200)
                                                    $("td:eq(3)", nRow).css("font-weight", "bold");
                                                    if (parseFloat(aData[3]) >= 100)
                                                    $("td:eq(3)", nRow).css("background-color", "#9BF59B");
                                                     }'),
                                   initComplete = JS(
                                     "function(settings, json) {",
                                     "$(this.api().table().header()).css({'background-color': '#949DA6', 'color': '#000'});",
                                     "}")
                                    )
      )
    })
  }
)

Fail to preserve Date object

If a column of a data frame is Date or POSIXct or POSIXlt-class vector, they will be printed as integers in the column.

library(DT)
datatable(data.frame(date = seq(as.Date("2015-01-01"), by = "day", length.out = 5), x = 1:5))

will produce a DataTable like

date    x
16436   1
16437   2
16438   3
16439   4
16440   5

The same thing does not happen with knitr::kable:

> knitr::kable(data.frame(date = seq(as.Date("2015-01-01"), by = "day", length.out = 5), x = 1:5))


|date       |  x|
|:----------|--:|
|2015-01-01 |  1|
|2015-01-02 |  2|
|2015-01-03 |  3|
|2015-01-04 |  4|
|2015-01-05 |  5|

To be continued...

Just a request that I (and probably many others) am looking forward to the completion of the vignette

Number formatters

Provide simple R syntax so users do not need to write JavaScript to format numbers, e.g.

datatable(...) %>%
  format_col(c(1, 3), type = c('currency', 'percentage'), sep = c(',', ''), before = c('$', ''), after = c('', '%'))
# or column by column
datatable(...) %>%
  format_col(1, 'currency', sep = ',', before = '$') %>%
  format_col(3, 'percentage')

Ideas from @tareefk

Data tables no longer appearing. jsonlite issue?

Have shiny app which uses DT and had been running smoothly but now no longer displays table. I get error

Warning in renderDataTable({ :
  Arguments in addition to 'expr', 'env', and 'quoted' are ignored. If you came from             shiny::renderDataTable(), you may want to pass these arguments to DT::datatable() instead. See http://rstudio.github.io/DT/shiny.html for more info.

If I run your minimal example from that link, I similarly have no table produced and get a warning

 library(shiny)
shinyApp(
  ui = fluidPage(DT::dataTableOutput('tbl')),
  server = function(input, output) {
    output$tbl = DT::renderDataTable({
      DT::datatable(iris, options = list(lengthChange = FALSE))
    })
  }
)

Note: the specification for S3 class โ€œAsIsโ€ in package โ€˜jsonliteโ€™ seems equivalent to one from package       โ€˜RJSONIOโ€™: not turning on duplicate class definitions for this class.

I have recently updated jsonlite so wonder if this is the issue

R version 3.1.2 (2014-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_Canada.1252 LC_CTYPE=English_Canada.1252 LC_MONETARY=English_Canada.1252
[4] LC_NUMERIC=C LC_TIME=English_Canada.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] shiny_0.11.1

loaded via a namespace (and not attached):
[1] digest_0.6.8 DT_0.0.35 htmltools_0.2.6 htmlwidgets_0.3.3 httpuv_1.3.2 jsonlite_0.9.16
[7] magrittr_1.5 mime_0.3 R6_2.0.1 Rcpp_0.11.5 RJSONIO_1.3-0 rstudioapi_0.3.1
[13] tools_3.1.2 xtable_1.7-4 yaml_2.1.13

Shiny+DT in Rmarkdown

Much respect for creating DT package!
I've read yout tutorail and I am aware that there are just plans for integration with shiny but maybe this functionality might already exist somehow.

Is there a way of creating interactive html document, created in markdown (as written here
http://shiny.rstudio.com/articles/interactive-docs.html ) in which there will be a shiny app reactively working with DT so that data argument in datatable function would be a reactive argument like in example below:

Now this looks to not work, but this maybe is fault of my low knowledge about shiny and DT.
Thanks for help.


---
runtime: shiny
output:
  html_document:
    fig_width: 12
    fig_height: 8

---

```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(comment="", message=FALSE, echo=FALSE, fig.width=12, fig.height=8,tidy.opts=list(keep.blank.line=TRUE, width.cutoff=80),options(width=90))
```


```{r, eval=FALSE}
library(devtools)
if (!require("DT")) devtools::install_github("rstudio/DT")
```

```{r}
source("script.R")
library(DT)
load("dataSet.rda")
```
```{r}
selectInput("this", "name",
            choices = list("statid", "pvid"),
            selected="statid",
            multiple=TRUE)
```

```{r}
which <- reactive({dataSet[, input$this]})

reactive({
datatable(head(which()))
})
```

A more general format* function?

Oftentimes we just want to add commas to a column without adding a prefix. Right now we can just do myTable %>% formatCurrency("myCol", currency = "", interval = 3, mark = ","), which works perfectly fine albeit with an awkward name. This particular use case might not warrant another tpl* definition, but I wanted to see if others have any thoughts on this, perhaps replacing formatCurrency with a more general alternative?

Embed HTML

I'm trying to embed Facebook posts into a data table within shinydashboard, but while the table appears, it appears to just have empty rows when escape=FALSE. I've checked and the HTML code that is shown in the table (when escape=TRUE) actually produces a result on its own.

Any idea how I can fix this?

shinyServer(function(input, output, session) {
...
output$tb1 <-  DT::renderDataTable({
  text <-fileData()
  p = matrix(sapply(1:length(text), function(i) {text[i]}),length(text))
  DT::datatable(p, escape=FALSE,rownames = FALSE, colnames='Posts', options=list(scrollY=500))})
...

ui.R

...
DT::dataTableOutput("tb1")
...

DataTables 1.10.7

TODO

  • #36 (class = "compact")
  • DataTables/DataTables#526 (Shift + Click to remove sorting)

Install in version 3.1

Hi,

I am doing a project and I would love to use DT. I need to stay in version R 3.1.0

Is it any way I can use this version?

THanks

No datatable if nrow == 1

I've been playing around with DT and I think the package is great!

I have come across an issue and I'm not sure if this is a feature or bug. I can't seem to generate a html table if the data.frame only has one row.

This doesn't print:

DT::datatable(data = data.frame(a = 1, b = 2, c = 3))

I have tried to to set options(list(iDisplayLength = 1)) but this doesn't help.

This does print:

DT::datatable(data = data.frame(a = c(1,2 ), b = c(2, 3), c = c(3, 4)))

Need help with TableTools

I'm trying to add TableTools to my little example and getting an error

library(DT)
# a custom table container
sketch = htmltools::withTags(table(
  class = 'display',
  thead(
    tr(
      th(rowspan = 2, 'Current Industry'),
      th(colspan = 3, 'Share of Workers'),
      th(colspan = 3, 'Share of Workers w/a Pro Cert (Q1)'),
      th(colspan = 3, 'Share of Workers w. Certificate (Q10)')
    ),
    tr(
      lapply(rep(c('Overall', 'Male', 'Female'), 3), th)
    )
  )
))
table1 = structure(c(4570, 8980, 6e-04, 0.0067, 0.8455, 0.1154, 0.1545, 
                     0.8846, 0.6998, 0.6348, 0.9416, 0.1349, 0.0584, 0.8651, 0.1742, 
                     0.2279, 1, 0.1568, 0, 0.8432), .Dim = c(2L, 10L), .Dimnames = list(
                       NULL, c("industry", "Overall1", "Male1", "Female1", "Overall2", 
                               "Male2", "Female2", "Overall3", "Male3", "Female3")))

datatable(table1, extensions = 'TableTools', 
  filter = 'top', container = sketch, caption = 'Table 1: Certification by industry',
          rownames = FALSE, 
  options = list(pageLength = 15, lengthMenu = c(5, 10, 15, 50, 100)), 
  dom = 'T<"clear">lfrtip',
  tableTools = list(sSwfPath = copySWF())) %>%
  formatPercentage(2:10, 2)

What am I doing wrong?

Thanks!

access sorting/filtering information?

I just wanted to check if accessing information on user input to DT (searches, sorting, etc.) is possible (see earlier SO questions below).

(Somewhat) related question: If an app has only one user, is DT more efficient at sorting and filtering data than dplyr? If not, could dplyr be used on the backend to generate the tabular information to be shown in the browser?

http://stackoverflow.com/questions/26348089/store-dataset-filtered-using-datatables-in-shiny-in-app
http://stackoverflow.com/questions/26709821/save-filter-based-on-user-inputs-to-data-tables

CSV, Excel, etc buttons not working

I posted an example app here:

https://ignacio.shinyapps.io/shiny_filter/

When I click the buttons (expect for print) nothing happens)

This is my server:

library(shiny)
library(DT)
library(dplyr)
set.seed(422015)
DF1 <- data.frame(V1=sample(x = c("A1", "A2", "B2", "B4", "C9"), size = 100, replace = T),
                  V2=runif(n = 100,min = -100, max = 100))
DF1 %>%
  group_by(V1) %>%
  summarise(mean=mean(V2)) %>%
  datatable()

shinyServer(function(input, output) {
  observe({

    output$tbl = renderDataTable({
      DF1 %>%
        filter(V2>input$slider2[1], V2<input$slider2[2], 
               V1 %in% input$checkGroup) %>%
        group_by(V1) %>%
        summarise(mean=mean(V2)) %>%
        datatable(extensions = 'TableTools', 
                  rownames = FALSE, 
                  options = list(pageLength = 5, lengthMenu = c(5, 10, 15, 50, 100),
                                 dom = 'T<"clear">lfrtip',
                                 tableTools = list(sSwfPath = copySWF())
                  ))
    })


  })

})

This is my ui:

library(shiny)
shinyUI(fluidPage(
  fluidRow(
    column(4,

           # Copy the line below to make a slider range 
           sliderInput("slider2", label = h3("Slider Range"), min = 0, 
                       max = 100, value = c(-100, 100)),
           checkboxGroupInput("checkGroup", label = h3("Checkbox group"), 
                              choices = list("A1" = "A1", "A2" = "A2", "B2" = "B2", "B4"="B4", "C9"="C9"),
                              selected = c("A1", "A2", "B2", "B4", "C9"))
    )
  ),
  hr(),
  fluidRow(
    DT::dataTableOutput('tbl')
  )
))

What am I doing wrong? Thanks!

The value of the datatable::rownames parameter affects 'target' indices

I can understand why this is happening, but I think this is unintentional/undesired behavior.

A simple example is ordering the output on a particular column.

This:

datatable(mtcars, options=list(order=list(list(3, 'asc'))))

orders mtcars by its 3rd column (disp), but this:

datatable(mtcars, options=list(order=list(list(3, 'asc'))), rownames=FALSE)

will order it by its 4th column (hp)

Also, the targets values in columnDefs are equally affected, this centers Sepal.Width:

datatable(iris, options=list(
  columnDefs=list(
    list(className = 'dt-center', targets = 2)
  )))

and this centers Petal.Length

datatable(iris, rownames=FALSE, options=list(
  columnDefs=list(
    list(className = 'dt-center', targets = 2)
  )))

Doesn't play well with knitr caching

If I want to use datatable inside an R Markdown chunk, caching fails.

Here's an example document:


---
title: "foo"
output: html_document

---

```{r, cache=TRUE}
DT::datatable(data.frame(x=runif(50),y=runif(50)))
```

The error I get on trying to knit this is:

Quitting from lines 7-8 (foo.Rmd) 
Error in wrap.knit_asis(X[[2L]], ...) : 
  The code chunk 'unnamed-chunk-1' is not cacheable; please use the chunk option cache=FALSE on this chunk
Calls: <Anonymous> ... wrap -> wrap.list -> lapply -> FUN -> wrap.knit_asis
Execution halted

Is there an Editor extension available for the DT package

I love this package. I combined several extensions and it really helps my app look great and function.

I thought KeyTable would allow me to edit, but it just navigates and highlights.

Is there an editor extension available or coming soon.

Thanks!
Mike

Save datatable to html file

Is there a way to save a table I just created to a html file so that I can visualize it in a browser?
Suppose I have a table

y <- DT::datatable(x)
y

When I see the table in the Viewer of Rstudio I can export the table into a html file with the option "save as web page". Can I do the same with a function? I have tried to export this "y" variable using R2HTML and hwriter packages but I can't do it.

y <- DT::datatable(x)
# rstudio::viewer.save(y, type = "html") -> something like this

Thanks!

DT Column filters not visible when used with Scroller extension

Column filters when used together with Scroller extension, do not properly display range sliders/select lists.

I'm using DT v0.0.34.

my_data = data.frame(a = 1:50, b = rep(letters[1:10]))
my_data_dt = datatable(my_data,
                       extensions = c('TableTools','Scroller'), 
                       rownames = FALSE,
                       filter = "top",
                       options = list(scrollY = 350))
my_data_dt

Add global options

I'm producing a webpage that contains more than 5 tables. The default options of DataTable.js include paging: true. However, I want all tables to render without paging so I need to specify options = list(paging = FALSE) for each datatable() call, which is quite redundant.

I read the documentation but found no global options to alter the default options. For example,

options(DT.options = list(paging = FALSE))

Error with shiny example

Thanks for this. Definitely looking to the 'coming soons' in the tutorial

shiny::runApp(system.file('examples', 'DT-shiny', package = 'DT'))
Error in if (q$search[["value"]] != "") { : argument is of length zero

Respect rownames of a data frame

Previously, I use knitr::kable to render a data frame into markdown and customize the rmarkdown document to include DataTables.js. The produced tables in the document has its first column as the original row names of the input data frame.

When I switch to DT, as the following code shows, datatable() seems not to respect the row names of the data frame, producing undesired results.

> knitr::kable(mtcars[1:5, ])


|                  |  mpg| cyl| disp|  hp| drat|    wt|  qsec| vs| am| gear| carb|
|:-----------------|----:|---:|----:|---:|----:|-----:|-----:|--:|--:|----:|----:|
|Mazda RX4         | 21.0|   6|  160| 110| 3.90| 2.620| 16.46|  0|  1|    4|    4|
|Mazda RX4 Wag     | 21.0|   6|  160| 110| 3.90| 2.875| 17.02|  0|  1|    4|    4|
|Datsun 710        | 22.8|   4|  108|  93| 3.85| 2.320| 18.61|  1|  1|    4|    1|
|Hornet 4 Drive    | 21.4|   6|  258| 110| 3.08| 3.215| 19.44|  1|  0|    3|    1|
|Hornet Sportabout | 18.7|   8|  360| 175| 3.15| 3.440| 17.02|  0|  0|    3|    2|

The knitr output includes the row names, but the datatable output does not.

datatable(mtcars)

Is it possible to include the row names, if exist, as the first column?

Using extensions = 'Responsive' slows typing into search field

This is a really wonderful package - thank you! The only problem I have run in so far is that if I add extensions = 'Responsive', I can no longer type characters into the search field at a normal rate - is very slow. I am only an R programmer (and not a great one at that) so any suggestions you might have would be great. Thanks!

strange interaction of htmlwidget packages


---
title: "Toy"
output: html_document

---

I noticed I was having trouble getting the metricsgraphics package to render and finally isolated the issue to formatCurrency() within DT

specifically, if one invokes a plot BEFORE the datatable, there's no issue for either widget, or any subsequent widgets later in the document

however if the datatable is invoked first WITH formatCurrency(), as below, the plot fails to render

```{r}
library("htmltools")
library("htmlwidgets")
library("DT")
library("metricsgraphics")

###mjs_plot fails, but run the plot first and it succeeds###
datatable(mtcars) %>% formatCurrency('hp')

mtcars %>% mjs_plot(x = wt, y = mpg) %>% mjs_point(color_accessor = carb)

#datatable(mtcars) %>% formatCurrency('hp')

```

using footerCallback to get column sums

I am trying to get column sums in the footer of a DT. I have read this page which talks about the option I need to set. So based on this I wrote the following R code:

library(DT)

d <- structure(list(ie_8_lower = c(0, 1, 1, 0, 0, 1, 1, 0), ie_9_higher = c(0, 
1, 0, 1, 0, 1, 0, 1), other = c(0, 1, 0, 0, 1, 0, 1, 1), buyers = c(4, 
2830, 123934, 2122766, 14346811, 10338, 37112, 357695), gmb_usd = c(640.25, 
1606175.85, 10970296.87, 192057195.09, 1215378720.43, 2250239.71, 
8800844.81, 72972772.59), buyer_share_pct = c(0, 0.02, 0.73, 
12.49, 84.39, 0.06, 0.22, 2.1), gmb_share_pct = c(0, 0.11, 0.73, 
12.77, 80.81, 0.15, 0.59, 4.85)), class = "data.frame", row.names = c(NA, 
-8L), .Names = c("ie_8_lower", "ie_9_higher", "other", "buyers", 
"gmb_usd", "buyer_share_pct", "gmb_share_pct"))

sketch <- htmltools::withTags(table(
  tableHeader(d),
  tableFooter(d)
))

opts <- list( 
  footerCallback = JS(
    "function( tfoot, data, start, end, display ) {",
      "var api = this.api();",
      "$( api.column( 5 ).footer() ).html(",
        "api.column( 5 ).data().reduce( function ( a, b ) {",
          "return a + b;",
        "} );",
        ");",
      "}"))

datatable(d, container = sketch, options = opts)

When this renders I do not see any table displayed to the browser - the html that is generated looks like this:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="lib/htmlwidgets-0.3.2/htmlwidgets.js"></script>
<script src="lib/jquery-1.11.1/jquery.min.js"></script>
<link href="lib/datatables-1.10.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="lib/datatables-1.10.5/js/jquery.dataTables.min.js"></script>
<script src="lib/datatables-binding-0.0.21/datatables.js"></script>

</head>
<body style="background-color:white;">
<div id="htmlwidget_container">
  <div id="htmlwidget-2225" style="width:100%;height:auto;" class="datatables"></div>
</div>
<script type="application/json" data-for="htmlwidget-2225">{ "x": {
 "data": [
 [ "1", "2", "3", "4", "5", "6", "7", "8" ],
[                 0,                 1,                 1,                 0,                 0,                 1,                 1,                 0 ],
[                 0,                 1,                 0,                 1,                 0,                 1,                 0,                 1 ],
[                 0,                 1,                 0,                 0,                 1,                 0,                 1,                 1 ],
[                 4,              2830,            123934,           2122766,          14346811,             10338,             37112,            357695 ],
[            640.25,        1606175.85,       10970296.87,      192057195.09,     1215378720.43,        2250239.71, 8800844.810000001,       72972772.59 ],
[                 0,              0.02,              0.73,             12.49,             84.39,              0.06,              0.22,               2.1 ],
[                 0,              0.11,              0.73,             12.77,             80.81,              0.15,              0.59,              4.85 ] 
],
"isDF": true,
"container": "<table>\n  <thead>\n    <tr>\n      <th>ie_8_lower</th>\n      <th>ie_9_higher</th>\n      <th>other</th>\n      <th>buyers</th>\n      <th>gmb_usd</th>\n      <th>buyer_share_pct</th>\n      <th>gmb_share_pct</th>\n    </tr>\n  </thead>\n  <tfoot>\n    <tr>\n      <th>ie_8_lower</th>\n      <th>ie_9_higher</th>\n      <th>other</th>\n      <th>buyers</th>\n      <th>gmb_usd</th>\n      <th>buyer_share_pct</th>\n      <th>gmb_share_pct</th>\n    </tr>\n  </tfoot>\n</table>",
"options": {
 "footerCallback": "function( tfoot, data, start, end, display ) {\nvar api = this.api();\n$( api.column( 5 ).footer() ).html(\napi.column( 5 ).data().reduce( function ( a, b ) {\nreturn a + b;\n} );\n);\n}",
"columnDefs": [
 {
 "orderable": false,
"targets":                 0 
},
{
 "className": "dt-right",
"targets": [                 1,                 2,                 3,                 4,                 5,                 6,                 7 ] 
} 
],
"order": [],
"autoWidth": false 
},
"callback": "function(table) {\nreturn table;\n}",
"colnames": [ " ", "ie_8_lower", "ie_9_higher", "other", "buyers", "gmb_usd", "buyer_share_pct", "gmb_share_pct" ] 
},"evals": [ "options.footerCallback", "callback" ] }</script>
<script type="application/htmlwidget-sizing" data-for="htmlwidget-2225">{ "viewer": {
 "width": "100%",
"height": "auto",
"padding":                15,
"fill": false 
},"browser": {
 "width": "100%",
"height": "auto",
"padding":                40,
"fill": false 
} }</script>
</body>
</html>

What am I doing wrong here?

Fix sorting of columns in scientific notation

These columns are parsed as characters in the output, and the sorting is hosed. A simple solution would be to use the scientific sorting plugin available from datatables.net.

An example is shown below. Try to sort on the p columns and you'll see what is the what:

p <- sprintf('%.2fe-%d',
             sample(seq(-1, 1, by=0.05), length(letters)),
             sample(1:10, length(letters), replace=TRUE))

df <- data.frame(name=letters, score=rnorm(letters), p=as.numeric(p))
datatable(df)

Specifying Column width

I am trying to adjust the column width for given columns. I am not sure what to use as the units on width or how to specify width.

On the DT site, it mentions it accepts any CSS value, I tried '30%',
http://datatables.net/reference/option/columns.width

I have also tried '150px', just a number like 200 (no quotes). Nothing changes the width.

What ever I specify for width displays the same out put.

DeptEditDT <- datatable(
  df, rownames=FALSE,
  extensions = list(Scroller=NULL, TableTools=NULL, FixedColumns=list(leftColumns=2)),
  options = list(
    dom = 'T<"clear">lfrtip',
    columnDefs = list(list(width = '20%', targets = list(2,3,4))),
    deferRender=TRUE,
    scrollX=TRUE,scrollY=400,
    scrollCollapse=TRUE,
    pageLength = 100, lengthMenu = c(10,50,100,200),
    tableTools=list(sSwfPath = copySWF('www'),aButtons=c('copy','csv','print'))
  )
)

In another section of code, I have a simpler DT and also tried to change the width here thinking the list of combined extensions was somehow getting in the way. Whatever I specify for width the column stays the same.

PrgEditDT<-datatable(df, rownames=FALSE, 
                       options = list(dom = 't',
                       columnDefs = list(list(width = '40%', targets = list(2,3,4)))))

Link in the table

Hi there,

Is it possible to put links as a content in the datatable?

filter boxes supported?

Are filter boxes below each column still supported? Even more interesting, is it possible to but a shiny input (e.g., slider or selectInput) above or below each column?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.