PACKAGE INSTALLATION & DATA FRAME
The first thing you have to do is install and load the DT package. Moreover, we need a dataset to work with. The dataset we chose in our case is “Iris”, which is the famous (Fisher’s or Anderson’s) iris data set. It gives the measurements in centimeters of the variables sepal length and width, petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris Setosa, Versicolor, and Virginica. We will also use the mtcars dataset, which was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models).
You can use
head() in order to see the variables of your dataset.
The main function in this package is
datatable(). Everything begins from here.
Tables with CSS
With the class argument, we can set the CSS class of a table. By default, these are enabled: row striping, row highlighting on mouse over, row borders, and highlighting ordered columns. You can choose a different combination of CSS classes:
datatable(head(iris), class = 'cell-border stripe')
The row names of your dataset will be displayed by default in the first column of your table. You can hide them by using
rownames = FALSE. You can also change row names.
datatable(head(mtcars), rownames = FALSE)
datatable(head(mtcars), rownames = head(LETTERS))
By default, the column names of the data are displayed in the table, but you can change them in some ways. For example, you can replace the column names like this.
datatable(head(iris), colnames = c('One', 'Two', 'Three', 'Four', 'Five'))
The second option is to change only selected column names by specifying them either by name or by position.
datatable(head(iris), colnames = c('One' = 'Sepal.Width'))
datatable(head(iris), colnames = c('Two' = 2, 'Four' = 4))
If you want to change the first column name, which is white space by default, you can do it with:
datatable(head(iris), colnames = c('ID' = 1))
You can add a table caption via the caption argument. It can be either a character vector or a tag object.
caption = 'Table 1: This is a simple caption for the table.'
Except for the global filter that is provided on the top right of the data table by default, no other column filters are provided. In the example below, we add a new filter. In order to display it as it is initially not displayed, since
filter = 'none', you have to enable these filters by
filter = 'top' or
'bottom', depending on where you want to put the filters.
datatable(iris, filter = 'top'