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

Webdesign & UX

Die umfassende Outlook Symbol Übersicht: Verstehen und Nutzen

AUTOR • May 16, 2026
DevOps & Deployment

So installierst du den ComfyUI Manager: Eine Schritt-für-Schritt-Anleitung

AUTOR • May 16, 2026
Full-Stack

Node-RED Anleitung: Der ultimative Einstieg in die visuelle Programmierung

AUTOR • May 16, 2026
Webdesign & UX

Die besten Methoden zum Virus entfernen: So bleibst du sicher im Netz

AUTOR • May 16, 2026
Performance & SEO

Effektive Nutzung von MS Teams Breakout Rooms für interaktive Meetings

AUTOR • May 16, 2026
Backend-Entwicklung

Pseudocode Beispiel: Effektives Programmieren leicht gemacht

AUTOR • May 16, 2026
Webdesign & UX

Numbered List Markdown

AUTOR • May 16, 2026
DevOps & Deployment

Home Assistant Standard Port: Ein umfassender Leitfaden zur Konfiguration und Sicherheit

AUTOR • May 16, 2026
Webdesign & UX

Die Schritte zum effektiven Tab Löschen in Browsern

AUTOR • May 16, 2026
DevOps & Deployment

So behebst du die Fehlermeldung 'Reolink Verbindung fehlgeschlagen'

AUTOR • May 16, 2026
Webdesign & UX

Die ultimative Anleitung zur Home Assistant Dokumentation in Deutsch

AUTOR • May 04, 2026
Frontend-Entwicklung

Node-RED Dashboard Aufrufen: Schritt-für-Schritt-Anleitung für Einsteiger

AUTOR • May 04, 2026
Webdesign & UX

Wie du dein Google Konto Altersbeschränkungen bestätigen kannst

AUTOR • May 04, 2026
Webdesign & UX

How to Use Friendly Captcha

AUTOR • May 04, 2026
Webdesign & UX

Die besten Schritte zur Installation des Realtek WLAN Treibers unter Windows 11

AUTOR • May 04, 2026
Datenbanken & ORM

So formatierst du FAT32 unter Linux: Eine Schritt-für-Schritt-Anleitung

AUTOR • May 04, 2026
APIs & Microservices

Webcatcher: Die revolutionäre Web-Scraping-Software

AUTOR • May 04, 2026
Webdesign & UX

Der Fully Kiosk Browser für Home Assistant: Eine umfassende Anleitung auf Deutsch

AUTOR • May 04, 2026
Performance & SEO

UTF-8 und Umlaute: Alles, was Sie wissen müssen

AUTOR • May 04, 2026
Webdesign & UX

So fügen Sie einen Haken in Outlook ein – Schritt-für-Schritt-Anleitung

AUTOR • May 04, 2026

Beliebte Beiträge

Performance & SEO

How to Encode Email Addresses

AUTOR • Dec 31, 2023
Performance & SEO

Excel Tabelle Größe Anpassen: So Optimieren Sie Ihre Arbeitsblätter

AUTOR • Jun 27, 2025
Webdesign & UX

Der Speicherort von Screenshots mit Windows + Shift + S: Alles, was du wissen musst

AUTOR • Jun 21, 2025
Webdesign & UX

Die besten Tipps, um alt Outlook zu bekommen und zu nutzen

AUTOR • Jun 12, 2025
DevOps & Deployment

Drucker einrichten und nutzen unter Windows 11: Eine Schritt-für-Schritt-Anleitung

AUTOR • Jun 23, 2025
Webdesign & UX

Die Lenovo Seriennummer finden: Eine Schritt-für-Schritt-Anleitung

AUTOR • Jun 26, 2025
Webdesign & UX

Outlook Übermittlungsfehler Löschen: Schritt-für-Schritt Anleitung zur Fehlerbehebung

AUTOR • Mar 11, 2026
Webdesign & UX

Serienbrief in Excel erstellen: Schritt-für-Schritt-Anleitung

AUTOR • Jul 01, 2025
Webdesign & UX

ANSI Converter: Simplify Text Formatting Effortlessly

AUTOR • Sep 04, 2024
Webdesign & UX

Excel CSV speichern mit Komma: Eine Schritt-für-Schritt-Anleitung

AUTOR • Jun 27, 2025
DevOps & Deployment

Microsoft SARA Tool Download: Alles, was Sie wissen müssen

AUTOR • Jun 18, 2025
Webdesign & UX

Outlook Klassisch Ansicht Einstellen: So gelingt es mühelos

AUTOR • Dec 15, 2025
Backend-Entwicklung

Wie Du Spotify mit 2FA absicherst: Eine Schritt-für-Schritt-Anleitung

AUTOR • Jul 11, 2025
Webdesign & UX

Adblocker unter Chrome für Android aktivieren: Schritt für Schritt Anleitung

AUTOR • Jun 08, 2025
Webdesign & UX

Effiziente Zusammenarbeit: Outlook Kalender Freigabe Anfordern leicht gemacht

AUTOR • Jun 08, 2025
DevOps & Deployment

Schritt-für-Schritt-Anleitung zum Einrichten eines PXE Boot Servers

AUTOR • Jul 16, 2025
Webdesign & UX

Dauerhaft die Menüleiste in Word einblenden: So geht's!

AUTOR • Jun 17, 2025
Webdesign & UX

5 einfache Methoden zum Einfügen von Zeilen in Excel-Tabellen

AUTOR • Jun 24, 2025
Frontend-Entwicklung

How to Write a Quote in Markdown

AUTOR • Feb 22, 2024
Webdesign & UX

Excel-Datei Schreibschutz aktivieren: So geht's!

AUTOR • Jun 17, 2025