FREE tools

Extending DT child rows example

Lukas Fuchs vor 3 Jahren Backend-Entwicklung 3 Min. Lesezeit

Short description of R package DT from its website:

The R package DT provides an R interface to the JavaScript library DataTables. R data objects (matrices or data frames) can be displayed as tables on HTML pages, and DataTables provides filtering, pagination, sorting, and many other features in the tables. 

In practice it means that we can easily publish interactable HTML tables to our reports, dashboards, blog posts etc. To learn more about DT visit https://rstudio.github.io/DT/. As you can imagine, there is lot of stuff you can do with your datatable, so even if you have used datatable() function for a while, I’ll highly recommend to take a look to the DT website. I found it to be full of useful examples.

Child Rows

There is an example of datatable with child rows published in DT website. The example, in turn, is adapted from DataTables website. In this post I will extend DT child rows example such that it will look more similar to the original. I start by downloading example data from DataTables website and save it as dt-export-ex.csv. Next I will load necessary packages, read data to R and add Employee ID variable to data.

library(tidyverse)
library(DT)
x <- readr::read_csv("dt-export-ex.csv")
x[["Employee ID"]] <- round(runif(nrow(x)) * 10000)

I use datatable2() function (see full code below) to embed datatable with child rows to this document:

datatable2(
  x = x, 
  vars = c("Employee ID", "Age", "Start date"),
  opts = list(pageLength = 5)
)

Show 5102550100 entriesSearch:

NamePositionOfficeSalary
Airi SatouAccountantTokyo$162,700
Angelica RamosChief Executive Officer (CEO)London$1,200,000
Ashton CoxJunior Technical AuthorSan Francisco$86,000
Bradley GreerSoftware EngineerLondon$132,000
Brenden WagnerSoftware EngineerSan Francisco$206,850

Showing 1 to 5 of 57 entries

Previous1234512Next

When clicking on the + sign we can see additional information about any given row. I think that datatable produced with databale2() function looks quite similar to original example. Also, the benefit of making a function out of it allows us to specify other options available for DT::datatable() functions, which hopefully makes datatable2() to fit better in my (or yours) workflow.

FUNS

Code for datatable2():

# datatable2 - datatable with child rows
datatable2 <- function(x, vars = NULL, opts = NULL, ...) {
  
  names_x <- names(x)
  if (is.null(vars)) stop("'vars' must be specified!")
  pos <- match(vars, names_x)
  if (any(map_chr(x[, pos], typeof) == "list"))
    stop("list columns are not supported in datatable2()")
  
  pos <- pos[pos <= ncol(x)] + 1
  rownames(x) <- NULL
  if (nrow(x) > 0) x <- cbind(' ' = '&oplus;', x)

  # options
  opts <- c(
    opts, 
    list(
      columnDefs = list(
        list(visible = FALSE, targets = c(0, pos)),
        list(orderable = FALSE, className = 'details-control', targets = 1),
        list(className = 'dt-left', targets = 1:3),
        list(className = 'dt-right', targets = 4:ncol(x))
      )
  ))
  
  datatable(
    x, 
    ...,
    escape = -2,
    options = opts,
    callback = JS(.callback2(x = x, pos = c(0, pos)))
  )
}

.callback2 <- function(x, pos = NULL) {
  
  part1 <- "table.column(1).nodes().to$().css({cursor: 'pointer'});"
  
  part2 <- .child_row_table2(x, pos = pos)
  
  part3 <- 
  "
   table.on('click', 'td.details-control', function() {
    var td = $(this), row = table.row(td.closest('tr'));
    if (row.child.isShown()) {
      row.child.hide();
      td.html('&oplus;');
    } else {
      row.child(format(row.data())).show();
      td.html('&ominus;');
    }
  });"
  
  paste(part1, part2, part3)
} 

.child_row_table2 <- function(x, pos = NULL) {
  
  names_x <- paste0(names(x), ":")
  text <- "
  var format = function(d) {
    text = '<div><table >' + 
  "

  for (i in seq_along(pos)) {
    text <- paste(text, glue::glue(
        "'<tr>' +
          '<td>' + '{names_x[pos[i]]}' + '</td>' +
          '<td>' + d[{pos[i]}] + '</td>' +
        '</tr>' + " ))
  }

  paste0(text,
    "'</table></div>'
      return text;};"
  )
}

Weitere Beiträge

Folge uns

Neue Beiträge

DevOps & Deployment

Xcode auf dem iPad: Der ultimative Leitfaden für Entwickler

AUTOR • Jun 16, 2026
Performance & SEO

So funktioniert das Zusammenfassen von Texten in Excel: Tipps und Tricks

AUTOR • Jun 16, 2026
DevOps & Deployment

BGInfo Autostart einrichten: So zeigst du Systeminfos bei jedem Login automatisch an

AUTOR • Jun 16, 2026
DevOps & Deployment

IP-Konzept: Grundlagen, Planung und Umsetzung für ein effektives Netzwerk

AUTOR • Jun 16, 2026
Webdesign & UX

Das iCloud Symbol: Eine visuelle Darstellung einer vernetzten Cloud einfach erklärt

AUTOR • Jun 16, 2026
Webdesign & UX

Die optimale Nutzung von Home Assistant mit Google Maps: So gehst du vor

AUTOR • Jun 16, 2026
Webdesign & UX

Lesezeichen sichern Firefox: So exportierst und schützt du deine Favoriten richtig

AUTOR • Jun 16, 2026
Frontend-Entwicklung

Hotmail auf dem iPhone einrichten: So funktioniert's mit dem Hotmail-Server

AUTOR • Jun 16, 2026
Webdesign & UX

Smileys in Word: Wie Sie Emotionen in Ihren Dokumenten einsetzen können

AUTOR • Jun 16, 2026
Frontend-Entwicklung

Convert Java to JavaScript: Essential Tips and Best Practices

AUTOR • Jun 16, 2026
Webdesign & UX

Wie du in Excel fortlaufende Wochentage mit Datumsangaben generierst

AUTOR • Jun 16, 2026
Performance & SEO

Tabelle erweitern Word: So vergrößerst du Tabellen sauber und schnell

AUTOR • Jun 16, 2026
Webdesign & UX

Magazine WordPress Theme: So wählst du das beste Theme für ein starkes Online-Magazin

AUTOR • Jun 16, 2026
APIs & Microservices

SPI TPM Header: So setzt du den SPI TPM Header für saubere Kommunikation im STM32 ein

AUTOR • Jun 16, 2026
Webdesign & UX

Screenshot mehrere Seiten: So erstellst du lange Screenshots auf mehreren Seiten

AUTOR • Jun 16, 2026
Webdesign & UX

Tastatur Aufbau: Alle Teile einer Tastatur einfach erklärt

AUTOR • Jun 16, 2026
Backend-Entwicklung

C++ Befehl einfach erklärt: Die wichtigsten Kommandos, Syntax und typische Fehler

AUTOR • Jun 16, 2026
Frontend-Entwicklung

How to Stop Typing Erases Next Letter: Fix the Overwrite Problem Fast

AUTOR • Jun 16, 2026
Frontend-Entwicklung

WP Download Manager: So nutzt du das WordPress-Plugin für Downloads, Leads und Kontrolle

AUTOR • Jun 16, 2026
Frontend-Entwicklung

Instagram Code eingeben: So funktioniert die Anmeldung mit Sicherheitscode

AUTOR • Jun 16, 2026

Beliebte Beiträge

Frontend-Entwicklung

Using a WordPress Photo Challenge Plugin

AUTOR • Mar 04, 2024
Webdesign & UX

Demystifying WordPress Code Blocks: A Comprehensive Tutorial

AUTOR • Mar 04, 2024
Webdesign & UX

How to Embed Calendly on WordPress

AUTOR • Jan 29, 2024
Webdesign & UX

How to Add a WordPress Search Widget to Your Site

AUTOR • Jan 18, 2024
Webdesign & UX

Outlook Autoarchivierung starten: So viel Platz schaffen Sie für wichtige E-Mails

AUTOR • Jun 26, 2025
DevOps & Deployment

Mount Points in Linux: Ein umfassender Leitfaden für Anfänger

AUTOR • Jun 26, 2025
Webdesign & UX

So fügen Sie ein Thunderbird-Konto hinzu: Schritt-für-Schritt-Anleitung

AUTOR • Jun 19, 2025
DevOps & Deployment

NVM Deinstallation leicht gemacht: Schritt-für-Schritt-Anleitung

AUTOR • Jun 17, 2025
DevOps & Deployment

Proxmox Backup Server Installation: Schritt-für-Schritt Anleitung für Einsteiger

AUTOR • Jun 14, 2025
Webdesign & UX

How to Choose a WordPress Partner

AUTOR • Jan 29, 2024
Backend-Entwicklung

Der Leitfaden für WMIC: So erhalten Sie den OA3X Original Product Key

AUTOR • Jul 16, 2025
DevOps & Deployment

Container Orchestrator: Der Schlüssel zur effizienten Verwaltung von Microservices

AUTOR • Jul 03, 2025
DevOps & Deployment

KVM vs. VirtualBox: Der ultimative Vergleich für virtuelle Maschinen

AUTOR • Jun 25, 2025
Webdesign & UX

Der ultimative Microsoft Surface Pro 5 Test: Lohnt sich die Investition?

AUTOR • Jun 24, 2025
Webdesign & UX

Die ultimative Anleitung für die Nutzung von Formeln in Word

AUTOR • Jun 19, 2025
Webdesign & UX

Die perfekte Anleitung zur Silbentrennung in Word aktivieren

AUTOR • Jun 18, 2025
Webdesign & UX

Magazeen WordPress Theme Review

AUTOR • Jan 08, 2024
Webdesign & UX

How to Format a Bulleted List in Markdown

AUTOR • Jan 08, 2024
DevOps & Deployment

WinRM aktivieren: Schritt-für-Schritt-Anleitung für Windows-Nutzer

AUTOR • Jul 16, 2025
DevOps & Deployment

So nutzen Sie 'pip show' zur Anzeige verfügbarer Versionen von Python-Paketen

AUTOR • Jul 03, 2025