block by timelyportfolio 49e92cc830e794d44018b0239612a466

hierarchy styling in formattable

Prompted by a tweet, I set out to write an example of illustrating hierarchy with the R package formattable. I used treemap to make some fake hierarchical data. Much of this code is cleaning the treemap data and can most likely be ignored.

library(treemap)
library(pipeR)
library(dplyr)
library(htmltools)

# make some fake data with treemap
tm <- random.hierarchical.data() %>>%
  treemap(
    index=c("index1","index2","index3"),
    vSize="x",
    draw=FALSE
  ) %>>%
  {.$tm} %>>%
  mutate_if(is.factor, as.character) %>>%
  mutate_at(vars(matches("index")),function(x){ifelse(is.na(x),1,x)}) %>>%
  arrange(index1,index2,index3) %>>%
  # much harder dealing with treemap
  #   than data you already have how you like it
  #   this step combines index cols into comma-delimited
  #   so we can apply some logic to get last value
  mutate(name = paste(index1,index2,index3,sep=","))

levelformatter <- formatter(
  "span",
  "class" = ~paste0("level",level),
  # this is the nasty step to get the lowest non-NA index
  #  you can probably ignore this and focus on above class piece
  #  if your data is already in proper format
  ~mapply(function(y,lvl){strsplit(y,",")[[1]][lvl]},name,level)
)

tm %>>%
  select(name,vSize,level) %>>%
  formattable(
    list(
      name = levelformatter,
      # hide level column
      level=FALSE
    )
  ) %>>%
  as.htmlwidget() %>>%
  tags$div(style="width:40%") %>>%
  tagList(
    tags$head(
      tags$style(
"
.level1{font-weight:bold;padding-right:100px;}
.level2{font-style:italic;padding-right:50px;}
.level3{font-size:80%;color:blue}
"
      )
    )
  ) %>>%
  browsable()