FREE tools

Extending DT child rows example

Lukas Fuchs vor 3 Jahren 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

Beitrag

Using a 404 Error Checker

AUTOR • Apr 23, 2026
Beitrag

Outlook automatisch starten in Windows 11: Eine Schritt-für-Schritt-Anleitung

AUTOR • Apr 23, 2026
Beitrag

How to Format Your Text With Markdown Quotes

AUTOR • Apr 23, 2026
Beitrag

Free WordPress Editor

AUTOR • Apr 23, 2026
Beitrag

How to Fix the Empty Reply From Server Error

AUTOR • Apr 23, 2026
Beitrag

Can't PreventDefault Inside Passive Event Listener

AUTOR • Apr 23, 2026
Beitrag

How to Fix a "F.TXT Js" Problem

AUTOR • Apr 23, 2026
Beitrag

How to Remove the Player Location Check Plugin

AUTOR • Apr 23, 2026
Beitrag

Scan Website For Broken Links

AUTOR • Apr 23, 2026
Beitrag

Pagelayer Vs Elementor - Which WordPress Theme Should You Choose?

AUTOR • Apr 23, 2026
Beitrag

Ethernet Kabel Belegung: Übersicht und Anleitung für Laien

AUTOR • Apr 20, 2026
Beitrag

RJ45-Steckerbelegung: So verkabeln Sie Ethernet-Kabel fachgerecht

AUTOR • Apr 20, 2026
Beitrag

Hochgestellte Zahlen ganz einfach eingeben: Die besten Tastenkombinationen

AUTOR • Apr 15, 2026
Beitrag

So nutzen Sie CMD, um Geräte im Netzwerk anzuzeigen

AUTOR • Apr 15, 2026
Beitrag

Die richtigen Firewall-Ports für WSUS: So konfigurieren Sie Ihre Sicherheitsrichtlinien

AUTOR • Apr 15, 2026
Beitrag

Das perfekte Energie Dashboard: Home Assistant individuell anpassen

AUTOR • Apr 15, 2026
Beitrag

So kopierst du Tabellen in Word mit der richtigen Formatierung

AUTOR • Apr 15, 2026
Beitrag

Smileys in Word Einfügen: So geht's einfach und schnell!

AUTOR • Apr 15, 2026
Beitrag

Home Assistant auf Ubuntu installieren: Schritt-für-Schritt-Anleitung

AUTOR • Mar 26, 2026
Beitrag

Excel: Zellen bis zum Ende markieren – So gelingt’s mühelos!

AUTOR • Mar 26, 2026

Beliebte Beiträge

Beitrag

WLAN-Antenne selbst bauen – Schritt-für-Schritt-Anleitung im PDF

AUTOR • May 09, 2024
Beitrag

So änderst du die Zeit des Sperrbildschirms in Windows 11 – Ein umfassender Guide

AUTOR • Jun 27, 2025
Beitrag

Outlook Konto gesperrt? So behebst du das Problem schnell und einfach!

AUTOR • Jun 19, 2025
Beitrag

So integrierst du die Home Assistant App auf Windows – Eine Schritt-für-Schritt-Anleitung

AUTOR • Dec 15, 2025
Beitrag

Word Seiten ausblenden: So funktioniert's einfach und schnell

AUTOR • Jun 14, 2025
Beitrag

optimal-website-performance-seo-checker-audit-guide-xdb

AUTOR • Feb 08, 2024
Beitrag

Wie du Home Assistant Token richtig nutzt: Ein umfassender Leitfaden

AUTOR • Jun 14, 2025
Beitrag

Excel: Zellen nach Farbe wertvoll machen – Mit diesen Tricks wird's einfach!

AUTOR • Jun 18, 2025
Beitrag

Tastaturbelegung ändern in Windows 11: So einfach geht's!

AUTOR • Jun 23, 2025
Beitrag

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

AUTOR • Jun 27, 2025
Beitrag

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

AUTOR • Jun 12, 2025
Beitrag

Die ultimative Anleitung zur Home Assistant Dokumentation in Deutsch

AUTOR • Jun 14, 2025
Beitrag

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

AUTOR • Jun 27, 2025
Beitrag

Webcatcher: Die revolutionäre Web-Scraping-Software

AUTOR • May 09, 2024
Beitrag

How to Use Friendly Captcha

AUTOR • Feb 22, 2024
Beitrag

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

AUTOR • Jan 14, 2026
Beitrag

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

AUTOR • Jun 14, 2025
Beitrag

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

AUTOR • Jun 23, 2025
Beitrag

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

AUTOR • Apr 12, 2025
Beitrag

Pseudocode Beispiel: Effektives Programmieren leicht gemacht

AUTOR • Sep 27, 2024