class: center, middle, inverse, title-slide # Workshop: Making Static and Dynamic Websites with R ## A brief Introduction to the Packages Blogdown and Shiny ### Gustavo Varela Alvanrega ### Pacific Northwest National Laboratory ### 2019-07-22 (updated: 2019-07-22) --- class: center, middle, inverse # R --- # What is R? - R is a language and environment for statistical computing and graphics. - R provides a wide variety of statistical and graphical techniques, and is highly extensible. - This extensibility allowed the creation of packages like `blogdown` and `shiny` that combine the statistical power of R with the need of web pages/apps we have today. --- class: center, middle, inverse # blogdown --- # Why blogdown? - You can create a static website in less than 10 minutes. - It uses R Markdown format - a file format for making dynamic documents with R that allows chunks of embedded R code - It runs using a static-site generator called “Hugo” which gives you a nice framework for building websites. --- # R Markdown Example You are recommended to use the [RStudio IDE](https://www.rstudio.com/products/rstudio/), but you do not have to. - Create a new R Markdown document from the menu `File -> New File -> R Markdown`; - Click the `Knit` button to compile it. --- # Hugo Framework - Hugo is a static-site generator, meaning that instead of generating your website from scratch everytime someone visits your page, the pages are already made and ready to go when someone arrives (more info here: https://gohugo.io/about/what-is-hugo/); - Extremely fast build times (< 1 ms per page) - Completely cross platform, with easy installation on macOS, Linux, Windows, and more - Renders changes on the fly as you develop - Powerful theming - Host your site anywhere - Straightforward **organization** for your projects, including website sections --- # Hugo Framework - Before we move forward, run: ```r install.packages("blogdown") ``` - Create a new Website using blogdown from the menu (if the menu is not showing, quit RStudio and start it again): `File -> New Project -> New Directory -> Website using blogdown`; - Select the main folder on your computer in which you want to save your website files and define a directory name for your new website; - At first, we will use the default Hugo Theme (we can change this later); - Click on 'Create Project'; - After the new project window opens, run these two commands in order: ```r blogdown::build_site() blogdown::serve_site() ``` --- # Hugo's Directory Structure - This is the main structrure of a generic Hugo template. - The way `blogdown` creates a website from Hugo and shows it to you will be a little different. But we can access this structure from whithin RStudio if we want to change anything. . ├── archetypes ├── config.toml ├── content ├── data ├── layouts ├── static └── themes --- # Archetypes - Files that contains preconfigured front matter (metadata - data about our content files; things like 'title', 'date', etc.); - If you look at the beggining of your R Markdown example file, you'll see it's metadata; - In our case, it creates the index.Rmd and _index.md files that you see in the root folder of your website (for the former) and at the main folder for each content section (for the latter); - We won't change these files. --- # config.toml - The configuration directives of your website: - The title of your website that will appear on Google Searches; - The language used on your website (English, Portuguese, etc.); - The Hugo theme that you used. - You can also define the sections of the header of your website, the usage of Google Analytics, etc. --- # Content - All content for your website will live inside this directory; - Each top-level folder in Hugo is considered a content section; - For example, if your site has three main sections — blog, articles, and tutorials - You will have three directories at: - content/blog; - content/articles; and - content/tutorials. - In our case, if you click `content -> post`, you'll see the R Markdown file (.Rmd) related to your blog post, and if you open it you'll see a structure similar to the one of the R Markdown file we created earlier. - If you change anything and save it, RStudio will automatically render the changes to your website. --- # Data - Stores any data that you'll use on your website; - In a way, it acts as a mini-database and it supports `JSON` files; - Since we are using R and databases from it, we won't use this. --- # Layouts - Stores templates in the form of `.html` files that specify how views of your content will be rendered into a static website; - Templates include your homepage, partials (header, footer of your page), single page templates (like 404 error pages), and more. - We won't change these files. --- # Static - Stores all the static content: images, CSS, JavaScript, etc. - A brief explanation on HTML, CSS, JavaScript (taken from https://www.getsmarter.com/blog/career-advice/difference-html-css-javascript/): - HTML, or HyperText Markup Language, is used to create the basic structure and content of a webpage; - CSS, or Cascading Style Sheets, is used for the design of a webpage – where everything is placed and how it looks; - JavaScript is used to define the interactive elements of a webpage that help to engage users - Hugo Templates already have these things (HTML, CSS, Javascript) defined, but we can change them if we want (this is advanced and we will not cover here - but you can ask me later). --- # Themes - Hugo provides a robust theming system that is easy to implement yet feature complete. You can view the themes created by the Hugo community on the Hugo themes website (https://themes.gohugo.io/). - Hugo themes are powered by the excellent Go template library and are designed to reduce code duplication. They are easy to both customize and keep in sync with the upstream theme. - In the case of the `themes` folder, it will contain the whole Directory Structure for that theme (with the 'architectures', 'layouts' folders) - only change this if you know what you are doing. --- # Publishing your website - RStudio creates a `public` folder inside the folder you created for your website. - This folder contains all the files necessary to publish your website - All you have to do is: - Log in to Netlify (https://www.netlify.com) - Drag your public folder to the dashed square area <img src="./presentation_v01_files/figure-html/netlify_box_v01.png" style="width: 80%" /> --- class: center, middle, inverse # shiny --- # What is shiny? - From `shiny`'s website (https://www.rstudio.com/products/shiny-2/): - Shiny is an open source R package that provides an elegant and powerful web framework for building web applications using R; - Shiny helps you turn your analyses into interactive web applications without requiring HTML, CSS, or JavaScript knowledge; - Shiny combines the computational power of R with the interactivity of the modern web. --- # Why shiny? - Easy to learn, easy to use; - 'Shiny' can help you go from sketch to a working application in less than a month (e.g., XMAT Prototype) without knowledge of HTML, CSS or Javascript. - It allows for the creation of dynamic user interfaces (UIs) that reacts to user input; - "In the simplest of terms reactivity/reactive programming is the ability of a program to compute outputs from a given set of user inputs." - "The ability of a shiny app to handle reactivity makes a two-way communication between the user and the existing information." - "Reactivity is applied in cases such as performing calculations, data manipulation, the collection of user information among other scenarios." - Downside: publishing a `shiny` app is more complicated than publishing a static page. <font size="1"> Quotes from https://towardsdatascience.com/get-started-with-examples-of-reactivity-in-in-shiny-apps-db409079dd11 </font> --- # How shiny works? - Shiny applications have two components: - A user interface (UI) object; and - A server function. - Your app can have these components on two separate files, called `ui.R` and `server.R`; or - On the same file, called `app.R`: - In this case, the UI and server componentes are passed as arguments to the `shinyApp` function that creates a Shiny app object from this UI/server pair. ```r # Empty Single File App library(shiny) # <- import shiny package ui <- fluidPage() # <- ui object server <- function(input, output){} # <- server function shinyApp(ui = ui, server = server) # <- creates a Shiny app ``` --- # Basic app and its elements - Go to `File -> New File -> Shiny Web App`, give your application a name, select 'Multiple File' and create a new app. --- # ui.R - This is where we construct the HTML part of our app; - For instance, run just this part from your code: ```r sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30) ``` - The ouput is: ```html <div class="form-group shiny-input-container"> <label class="control-label" for="bins">Number of bins:</label> <input class="js-range-slider" id="bins" data-min="1" data-max="50" data-from="30" data-step="1" data-grid="true" data-grid-num="9.8" data-grid-snap="false" data-prettify-separator="," data-prettify-enabled="true" data-keyboard="true" data-data-type="number"/> </div> ``` --- # ui.R - Panels - Shiny implemented the layout features availabe in Bootstrap; - Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development; - Panel functions are used to put a group of elements together into a single ‘panel’. ```r absolutePanel() conditionalPanel() fixedPanel() headerPanel() inputPanel() mainPanel() navlistPanel() sidebarPanel() tabPanel() tabsetPanel() titlePanel() wellPanel() ``` - Most of the panel functions return div tags with some class attributes defined in Bootstrap; - For example, if you type wellPanel in the R console, you’ll get `<div class="well"></div>`, which is the well class in Bootstrap. Source: https://bookdown.org/weicheng/shinyTutorial/ui.html --- # ui.R - Layout - Layout functions are used to organize panels and elements into an existing layout. - `fluidRow()`, `column()`: Creates rows and columns based on the bootstrap [grid system];  Source: https://bookdown.org/weicheng/shinyTutorial/ui.html --- # ui.R - Layout - `flowLayout()`: Lays out elements in a left-to-right, top-to-bottom arrangement;  Source: https://bookdown.org/weicheng/shinyTutorial/ui.html --- # ui.R - Layout - `sidebarLayout()`: Creates a layout with a sidebar and main area. (Most commonly used layout.);  Source: https://bookdown.org/weicheng/shinyTutorial/ui.html --- # ui.R - Layout - `splitLayout()`: Lays out elements horizontally, dividing the available horizontal space into equal parts (by default);  Source: https://bookdown.org/weicheng/shinyTutorial/ui.html --- # ui.R - Layout - `verticalLayout()`: Creates a container that includes one or more rows of content.  Source: https://bookdown.org/weicheng/shinyTutorial/ui.html --- # ui.R - Inputs - Inputs are given through control widgets; - These are web elements that users can interact with; - Widgets provide a way for your users to send messages to the Shiny app; - Shiny widgets collect values from the user. When a user changes the widget, the value will change as well. --- # ui.R - Inputs - The standard Shiny widgets are: <img src="./presentation_v01_files/figure-html/widgets.png" style="width: 80%" /> Source: https://bookdown.org/weicheng/shinyTutorial/ui.html --- # server.R - The function `shinyServer` has two arguments, `input` and `output`: ```r server <- function(input, output){} ``` - The `input` stores the values received by all the widgets in your app; - These values will be saved under the names same as the `inputId` of the widgets in ui.R. - The output contains all of the code needed to update the R objects in your app. - Shiny will automatically make an object **reactive** if the object uses an input value. --- # server.R - There are many pairs of *Output* and *render* functions defined in Shiny and they work together to add R output to the UI; - Which pair you'll use will depend on the object you want to render. Here are some standard pairs:  Source: https://bookdown.org/weicheng/shinyTutorial/server.html --- # server.R - Different packages have different names for their output and render functions. You'll have to check the package documentation for the approprieate function names. - For example, using the `plotly` package: ```r library(shiny) library(plotly) ui <- fluidPage( plotlyOutput(outputId = "plot") # <- output function: plotlyOutput ) server <- function(input, output) { output$plot <- # <- add 'plot' to the output list of objects renderPlotly({ # <- render function: renderPlotly plot_ly(mtcars, x = ~mpg, y = ~wt) }) } shinyApp(ui, server) ``` --- # Publishing your Shiny App - Shiny needs a special type of server to run, since it requires that R and RStudio are installed in that server; - The easiest way to plublish your app is to set up a free account at https://shinyapps.io (this is what we'll cover here); - You can also create your own shiny server using Linux (you'll have to buy a virtual machine at some cloud host, install R and RStudio in it and save your files there as well); - There's a package called `shinyproxy` that allows you to publish your apps using Dockers, but I haven't worked with it yet. --- # Publishing your Shiny App - Log into https://shinyapps.io - Go to `Dashboard` - On the `Dashboard` menu (on the right), go to `Account -> Tokens -> Add Token` - At the recently added token, click on `Show`, then `Show secret` and copy it to the clipboard. Hit `ok` and go back to RStudio. --- # Publishing your Shiny App - At either one of your shiny app files (ui.R or server.R), click the blue icon: <img src="./presentation_v01_files/figure-html/blueIcon.png" style="heigth: 80%" /> - Go to `Add New Account` select `ShinyApps.io`, paste the secret and `Connect Account`. - Choose a name for your app and click `Publish`. When it's done, it will open the published app on a new browser page. --- class: center, middle, inverse # Thanks! Slides created via the R package [**xaringan**](https://github.com/yihui/xaringan).