Zainab Alhosni-133464
2024-12-09
Introduction In this exercise, we will explore the functionality of the datatable package, create interactive tables using its features, and extend its functionality with a custom function.
Step 1: Package Discovery and Installation Installing and Loading the Package
# Install DT (if not already installed)
if (!requireNamespace("DT", quietly = TRUE)) {
install.packages("DT")
}
library(DT)
## Warning: package 'DT' was built under R version 4.4.2
Exploring the Package Documentation
## starting httpd help server ... done
Step 2: Creating an Interactive Table We will use the built-in mtcars dataset to create a basic interactive table.
Step 3: Customizing the Table You can add options like pagination, searching, and styling.
# Customizing the datatable
datatable(
mtcars,
options = list(
pageLength = 5,
searching = TRUE,
autoWidth = TRUE
),
caption = "Table 1: Custom Interactive Table of mtcars"
)
Step 4: Extending the Functionality Creating a Custom Function Define a function to add custom styles and features to a table.
customize_table <- function(data, title) {
datatable(
data,
options = list(
pageLength = 10,
dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
scrollX = TRUE
),
extensions = 'Buttons',
caption = title
)
}
# Applying the custom function
custom_table <- customize_table(mtcars, "Table 2: Extended Interactive Table")
custom_table
Step 5: Exploring Additional Features The DT package provides more functionalities, like formatting numbers and conditional styling.
# Conditional styling and formatting
datatable(
mtcars,
options = list(pageLength = 5),
caption = "Table 3: Styled Table"
) %>%
formatStyle(
'mpg',
backgroundColor = styleInterval(c(20, 30), c('red', 'yellow', 'green'))
)
Conclusion In this exercise, we:
Explored the datatable package and its documentation. Created interactive tables with DT. Customized and extended table functionalities using a custom function. This showcases the power of DT for creating highly customizable and interactive data tables in R.