R Flex Dashboards

Intro

  Creating “Dashboards” can be important when communicating insights from data to non-technical audiences. There are platforms like PowerBI and Tableau that can be utilized for data visualization, but there are ways - as far as I’m aware - to do just about everything you can do in those programs in R and R Studio. These are my notes on how to create a Flex Dashboard in R. Here are the links to the first and second video by the channel ‘CradleToGraveR’ on YouTube. A third video by Andrew Couch comparing {flexdashboard} and {shiny} dashboards revealed further interactive capabilities.

Set up

  First we need to proper R packages to create a dashboard. The videos cover {flexdashboard} so that’s what we’ll be using. They also recommend the DT package for creating tables that allow functions like filtering and searching to further strengthen the capabilities of the dashboard.

install.packages('flexdashboard')
install.packages('DT')

Open a Blank Dashboard

  Now that the packages have been installed, we can open a blank flexdashboard by selecting File > New File > R Markdown. Then instead of what I would normally do - name the file, ensure HTML is selected, and press OK - we’ll move down on the left side and select From Template which will open a list of templates that includes Flex Dashboard. Before we go any further, we’ll knit the document by either pressing the ‘Knit’ button in the top bar below the open file tabs, pressing the shortcut CTRL + SHIFT + k, or running the command rmarkdown::render("your-dashboard-file.Rmd") in the console. If you haven’t saved your new Rmd file, you’ll need to do that in this process. You should now have an html file with the same name as your Rmd file. The video recommends clicking on the html file and opening the file in your browser so you can see your dashboard at work. Any time we re-knit our Rmd file, the dashboard should update in our browser.

Layout

YAML

---
title: "YOUR-TITLE-HERE"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

  By default the orientation is set to divide the dashboard into columns and to fill the whole space.

Dashboard Sections

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

  This is a column, roughly 2/3 of the width of the dashboard (total width is 1,000). The long string of ‘-’ says ’everything until the next long string of ‘-’ will be contained in this column with a width of 650.’ You can also specify a column with a double hash tag ‘##’ in front of the word column rather than use the long string of dashes:

## Column {data-width=650}

  New charts are created with three hash tags ‘###’ as seen in the ‘Chart A’ example above

Column {data-width=350}
-----------------------------------------------------------------------

### Chart B



### Chart C



  R will automatically split the vertical dimension into as many equal parts as it can for the number of charts that are in that column. If you desire a chart to take up the entirety of the column, but still want the option to switch to another chart in that same column, you can add the ‘.tabset’ option inside the curly braces for that column:

Column {data-width=350, .tabset}

Creating a New Page

  Use a single hash tag ‘#’ to create a new page for your dashboard. Everything under this header until the next # header (or the end of the document) will be contained on that page.

# Second Page

Creating Content for the Fields

  Filling each of these fields with content is the same as you would for anything else in R or R Markdown. Code will go in the sections surrounded by ‘```{r}’. To make a new code section quickly, use the shortcut CTRL + ALT + i.

Value Boxes

  For cases when you just want one number displayed in a field, the valueBox(NUMBER) command can help the display be a little more aesthetically pleasing. You can add Font-Awesome icons by adding icon = "". For example, to put a single number in Chart B

### Chart B

'''{r}
valueBox(23, icon = 'fa-pencil')
'''

Gauges

  You may want to display some sort of meter in one of the fields. That can be achieved with the gauge(NUMBER, min = MINIMUM, max = MAXIMUM) command. You can further customize the colors to change under certain value conditions with

gauge(NUMBER, min = MIN, max = MAX,
      gaugeSectors(success = c(successMIN, successMAX),
                   warning = c(warningMIN, warningMAX),
                   danger = c(dangerMIN, dangerMAX))

Embedded HTML

  Just like with standard R Markdown, you can embed HTML to futher customize the look of your flexdashboard. For example, changing the color of your text in line with <font color='red'>My red text</font>

Interactive Tables with {DT}

  By default a data table created with {DT} enables searchability and navigating between the pages. There are times when you’ll want to enable things like the ability to download the data table in different formats. We can add these buttons using one of the {DT} extensions found on the package site:

datatable(
  iris, extensions = 'Buttons', options = list(
    dom = 'Bfrtip',
    buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
  )
)

dom = 'Bfrtip' assigns the location for all of the buttons, and the button names allow the extraction of the data in the listed formats. There is a huge amount of customization of form and function of these data tables. More details can be found on the package’s website.

Side Bars

  In order to create a side bar, which may be used for things like drop down menus, use:

## Column {.sidebar}

  Then you’ll need some kind of input for that sidebar. They used the ‘Penguins’ data set and created their drop down menu to shift between the penguin species

'''{r}
selectInput("v_species", label = "Species", choices = c('All', 'Adelie', 'Chinstrap', 'Gentoo'), selected = 'All')
'''

  And then they surrounded their static chart with a renderPlot({}) function to allow the selections on the sidebar to change what is displayed on their chart:

df <- penguins

renderPlot({
  df %>%
    select(-island, -sex) %>%  # remove unwanted columns
    pivot_longer(-species) %>%  # pivot longer along the species column 
    group_by(name) %>%  # grouping the penguins 
    mutate(value = scale(value)) %>%  # to scale as a percentage rather than a raw number
    ungroup() %>%
    
    filter(str_detect(species, if_else(inputs$v_species == "All", "", input$v_species))) %>%  
        # filter the data based on the selected innput from the other function
        # detects whether the input is one of the listed species, otherwise pull an input from our selectInput()
    
    ggplot(aes(x = value, y = name, fill = species)) +  # create out ggplot
      geom_density_ridges(alpha = 0.7) +  # use the ridges shape, setting some transparency
      theme(legend.position = 'top') +  # putting the legend at the top of the chart
      labs(y = "", x = "")  # remove the x and y labels
})

Conclusion

  The general sense I’m getting is that {flexdashboard} is great for quickly putting together a dashboard presentation, especially if the information has already in R Markdown format. {shiny} allows for greater control and capabilities, and can be a great followup if you need to expand your dashboard further. It looks like Andrew Couch has several videos on how to build dashboards with {shiny}, so that will be the subject of further exploration in the future.