1 min read

deeply nested functions

If, in teaching folks about the magrittr pipe operator, %>%, you’re looking for an in-the-wild example of deeply nested functions, our miner package (for connecting R to Minecraft, developed at the ROpenSci 2017 Unconference) has a good one:

setNames(data.frame(
    do.call(rbind,
            sapply(
                X = sub(",", "|", strsplit(string, '|', fixed = TRUE)[[1]], fixed=TRUE),
                FUN = strsplit,
                split = '|', fixed=TRUE,
                USE.NAMES = FALSE)),
    stringsAsFactors=FALSE),
    colnames)

This turns a character string like "121,hello everyone|4734,R mc_plot()" into a data frame like

string <- "121,hello everyone|4734,R mc_plot()"
colnames <- c("player", "message")

<<nested_func>>

That’s six functions deep: strsplit %>% sub %>% sapply %>% do.call %>% data.frame %>% setNames.