R Shiny Markdown



This R Markdown document is made interactive using Shiny. Unlike the more traditional workflow of creating static reports, you can now create documents that allow your readers to change the assumptions underlying your analysis and see the results immediately. Adjusting margins in your shiny document. Margins are by default set at a specific width for all shiny documents. Provide example code for R, Rshiny, Rmarkdown dashboard. Includes two selector inputs, one to choose which column of the daily trading data to use and the other to select which cryptocurrencies to plot.

The R plugin for PyCharm provides handy capabilities to work with the R Markdown files. With the interactive editor, you can quickly add executable chunks of R code, run and debug them, and produce the HTML output.

The plugin supports different markdown content: documents, notebooks, presentations, and Shiny (interactive markdown).

When you create a new *.rmd file, you can select the file type:

Each file is create with a specific header that depends on its type:

--- title: 'Untitled' author: < username > date: < the current date DD/MM/YYYY > output: rmarkdown::html_vignette ---

This header is used to render output in an HTML file. To modify the default header, edit the R Markdown template in the project Settings/Preferences.

In the R Markdown file you can add any context according to the Markdown syntax and some executable code chunks.

Add a code chunk

How To Use R Markdown

  1. To add a new R chunk to your R Markdown file, position the caret at any line or the code chunk, then click or press Ctrl+Alt+Insert. The following construct will be added below the selected line or chunk:

  2. Type any R code in the chunk.

    When adding R code to the chunk, use the code assistance features, such as code completion, code inspections, and quick fixes.

Once the code is added the execution actions become available through the Run menu in the gutter and in the chunk toolbar.

ItemDescription
Executes the current code chunk.
Debugs the current code chunk.
Executes all the code chunks above the current chunk.
Executes all the code chunk below the current chunk.
Shiny

Execute code chunks

  1. To execute a code chunk at the caret, click and select Run Chunk, or click on the chunk toolbar.

  2. When executing one chunk at a time, mind code dependencies. For example, the second chunk in the code fragment uses the variable defined in the first chunk.

    Click to execute all chunks above the currently selected chunk to make sure that all required variables are initialized.

  3. At any time you can click to execute all remaining code chunks in the file, or opt to the execution all code chunks at once by clicking .

  4. Preview and evaluate the results of the execution that are rendered below the chunk.

    You can also switch to the R Console to study variables in-detail.

  5. If needed, click to clear the execution results.

You can debug executable chunks in R Markdown files to detect and fix any errors in them.

R Shiny Markdown Pokemon Go

Debug code chunks

  1. Click the gutter to create breakpoints.

    Before debugging a particular code chunk, ensure that you have debugged all chunks with its code dependencies. Similar to running code chunks, you cannot perform debugging, if any of the variables used in the current chunk have not been initialized.

  2. Click on the chunk toolbar.

    Switch to the R Console. The debugging process stops at a breakpoint and you can preview the current results in the Variables window.

  3. Manage the debugging process with the debugging toolbar.

Shiny

You can create an HTML file that includes both the R Markdown source code and the results of its execution.

R Markdown Package

Generate the HTML output

  1. Click on the R Markdown toolbar.

  2. PyCharm creates an HTML file with the same name as the .rmd file. The R Markdown console reports on the task completion.

    By default, all output files are stored in the project root directory. If needed, select Custom from the list of the output directories on the R Markdown toolbar and specify an alternative location for the output files.

  3. Click to open the output file in the browser.

You can present your R markdown content in a form of presentation.

Build a presentation

  1. Create a new *.rmd file and select Presentation when specifying its type.

  2. Use ## headers to mark each new slide. The following code sample creates three content slides:

    ## Bar plot ```{r} mycars <- within(mtcars, {cyl <- ordered(cyl)}) ``` ```{r} cyls <- table(mycars$cyl) barplot(cyls, main='Car cylinder distribution', col = '#d4724e') ``` ## Pie ```{r} slices <- c(10, 12,4, 16, 10) lbls <- c('US', 'UK', 'Australia', 'Germany', 'France') mytable <- (slices) pie(slices, labels = lbls, main='Pie Chart of Countries') ``` ## Dot plot ```{r} dotchart(mtcars$drat,labels=row.names(mtcars),cex=.7, main='Rear axle ratio') ```
  3. Click to open the generated presentation in the browser.

You can also build R Markdown with interactive content by using Shiny.

Create interactive widgets with Shiny

  1. Create a new *.rmd file and select Shiny when specifying its type.

  2. Edit the code chunk in the template file or click to create a new code chunk.

  3. Add your Shiny code, for example, one sample from the Shiny Gallery:

    ```{r echo = FALSE} # Define UI for app that draws a histogram ---- ui <- fluidPage( # App title ---- titlePanel('Hello Shiny!'), # Sidebar layout with input and output definitions ---- sidebarLayout( # Sidebar panel for inputs ---- sidebarPanel( # Input: Slider for the number of bins ---- sliderInput(inputId = 'bins', label = 'Number of bins:', min = 1, max = 50, value = 30) ), # Main panel for displaying outputs ---- mainPanel( # Output: Histogram ---- plotOutput(outputId = 'distPlot') ) ) ) # Define server logic required to draw a histogram ---- server <- function(input, output) { # Histogram of the Old Faithful Geyser Data ---- # with requested number of bins # This expression that generates a histogram is wrapped in a call # to renderPlot to indicate that: # # 1. It is 'reactive' and therefore should be automatically # re-executed when inputs (input$bins) change # 2. Its output type is a plot output$distPlot <- renderPlot({ x <- faithful$waiting bins <- seq(min(x), max(x), length.out = input$bins + 1) hist(x, breaks = bins, col = '#75AADB', border = 'white', xlab = 'Waiting time to next eruption (in mins)', main = 'Histogram of waiting times') }) } shinyApp(ui, server) ```
  4. If any code line is highlighted, hover it over: you might have not the shiny package installed. Press Alt+Enter and install the missing package.

  5. Click to build the output.

Interactive R Markdown

5.3 Shiny

By adding Shiny to a dashboard, you can let viewers change underlying parameters and see the results immediately, or let dashboards update themselves incrementally as their underlying data changes (see functions reactiveFileReader() and reactivePoll() in the shiny package). This is done by adding runtime: shiny to a standard dashboard document, and then adding one or more input controls and/or reactive expressions that dynamically drive the appearance of the components within the dashboard.

Using Shiny with flexdashboard turns a static R Markdown report into an interactive document. It is important to note that interactive documents need to be deployed to a Shiny Server to be shared broadly (whereas static R Markdown documents are standalone web pages that can be attached to emails or served from any standard web server).

Note that the shinydashboard package provides another way to create dashboards with Shiny.

5.3.1 Getting started

The steps required to add Shiny components to a dashboard are:

  1. Add runtime: shiny to the options declared at the top of the document (YAML metadata).

  2. Add the {.sidebar} attribute to the first column of the dashboard to make it a host for Shiny input controls (note that this step is not strictly required, but this will generate a typical layout for Shiny-based dashboards).

  3. Add Shiny inputs and outputs as appropriate.

  4. When including plots, be sure to wrap them in a call to renderPlot(). This is important not only for dynamically responding to changes, but also to ensure that they are automatically re-sized when their container changes.

5.3.2 A Shiny dashboard example

Here is a simple example of a dashboard that uses Shiny (see Figure 5.7 for the output):

Markdown

FIGURE 5.7: An interactive dashboard based on Shiny.

R Shiny Markdown

The first column includes the {.sidebar} attribute and two Shiny input controls; the second column includes the Shiny code required to render the chart based on the inputs.

One important thing to note about this example is the chunk labeled global at the top of the document. The global chunk has special behavior within flexdashboard: it is executed only once within the global environment, so that its results (e.g., data frames read from disk) can be accessed by all users of a multi-user dashboard. Loading your data within a global chunk will result in substantially better startup performance for your users, and hence is highly recommended.

5.3.3 Input sidebar

You add an input sidebar to a flexdashboard by adding the {.sidebar} attribute to a column, which indicates that it should be laid out flush to the left with a default width of 250 pixels and a special background color. Sidebars always appear on the left no matter where they are defined within the flow of the document.

If you are creating a dashboard with multiple pages, you may want to use a single sidebar that applies across all pages. In this case, you should define the sidebar using a first-level Markdown header.

5.3.4 Learning more

Below are some good resources for learning more about Shiny and creating interactive documents:

  1. The official Shiny website (http://shiny.rstudio.com) includes extensive articles, tutorials, and examples to help you learn more about Shiny.

  2. The article “Introduction to Interactive Documents” on the Shiny website is a great guide for getting started with Shiny and R Markdown.

  3. For deploying interactive documents, you may consider Shiny Server or RStudio Connect: https://www.rstudio.com/products/shiny/shiny-server/.