How to create a Shiny app using SAS9API and R

  • Date September 19, 2019
  • Written by Vasilij Nevlev
  • Category R

This example shows how to create a Shiny app for a SAS dataset using SAS9API.

Shiny is an R package that allows you to build interactive web apps easily straight from RStudio.

Below you can see an example of Shiny app for Google trend index. Try changing index or date range and see how plot updates:

In this guide, we will build a similar app for SASHELP.STOCKS dataset.

Prerequisites

Before you start using this guide you’ll need the following:

  • Access to SAS9API proxy,
  • R and RStudio installed.

Step 1 – Getting the libraries needed

First we will need shiny package to create a Shiny app and ggplot2  package to create a plot. Also we will need rsas9api  package to send requests to SAS9API and to install it from GitHub we will need devtools  package.

Packages devtoolsshiny  and ggplot2 are available on CRAN, so if you don’t have them already installed run the following code:

install.packages("shiny")
install.packages("ggplot2")
install.packages("devtools")

And to get rsas9api  from GitHub run:

devtools::install_github("analytium/rsas9api")

Now let’s load our packages:

library(shiny)
library(rsas9api)
library(ggplot2)

Packages are loaded and we can go to the next step.

Step 2 – Defining connection properties for SAS9API proxy

To send requests to SAS9API endpoints you need to define:

  • URL for SAS9API proxy,
  • SAS workspace server name.

You can do that by replacing your_url  and your_server  in the following code and then running it.

sas9api_url <- "your_url" 
sas_workspace_server_name <- "your_server"

After specifying connection properties we can send requests to SAS9API.

Step 3 – Getting SAS dataset data

We will be using retrieve_data  function from rsas9api  package. This function allows us to get data from a SAS dataset and to store it.
To send a request using retrieve_data  function you will need to define:

  • library name of the dataset (“SASHELP” in our case),
  • dataset name (“STOCKS” in our case),
  • limit number: number of records to get from the dataset (we will use the maximum value of 10000),
  • offset number: number of records to skip from the beginning of dataset (we will leave it at 0),
  • asDataFrame flag (TRUE in our case, as we want our request to return a dataset).

Let’s run the code:

data_cars <- retrieve_data(url = sas9api_url, 
                           serverName = sas_workspace_server_name, 
                           libraryName = "SASHELP", 
                           datasetName = "STOCKS", 
                           limit = 10000, offset = 0, 
                           asDataFrame = TRUE)

Now that we have the data we can start creating the app.

Step 4 – Writing UI part of Shiny app

Shiny app consists of two main parts: server and UI. We will start with UI first.

Shiny has several options for UI layout – you can check the official cheat sheet for them. In this example, we will use fluid rows layout.

Our UI will have a title defined using titlePanel function. Then it will have three rows – we will use fluidRow for that. Rows, on the other hand, consist of columns.

The first column will contain our inputs:

  • drop-down list with values “IBM”, “Intel”, “Microsoft” using selectInput  function;
  • two date fields for start and end of the period defined with dateRangeInput  function.

The second column will have our outputs as five calculated statistics:

  • Number of records for the period;
  • Average of Open for the period;
  • Average of Close for the period;
  • Minimum of Low for the period;
  • Maximum of High for the period.

The second row will only contain the plot and the third row – output table.

Let’s run our code:

ui <- fluidPage(
            titlePanel("SASHELP.STOCKS"),

            fluidRow(column(width = 4,
                            selectInput(inputId = "selectStock",
                                        label = "Select stock",
                                        choices = c("IBM", "Intel", "Microsoft")),
                            dateRangeInput(inputId = "Dates",
                                   label = "Select date period",
                                   start = "1986-08-01",
                                   end = "2005-12-01")
                            ),

                     column(width = 7, offset = 1,
                            strong("Number of records for the period:"),
                            textOutput("number"),
                            strong("Average of Open for the period:"),
                            textOutput("av_open"),
                            strong("Average of Close for the period:"),
                            textOutput("av_close"),
                            strong("Minimum of Low for the period:"),
                            textOutput("min_low"),
                            strong("Maximum of High for the period:"),
                            textOutput("max_high")
                            )
                     ),

            fluidRow(column(width = 12,
                            plotOutput("plot1")
                            )
                    ),

            fluidRow(column(width = 12,
                            dataTableOutput("table1")
                            )
                     )
)

Now we have the UI for our Shiny app and we can start writing the server part.

Step 5 – Writing server part of Shiny app

Server part is actually the one that does all the calculations. So first we need to subset our dataset using the input data: start and end date of the period and stock name. And then we need to calculate our statistics and create our plot. Let’s do that using the following code:

server <- function(input, output) {
            datasubset <- reactive({
                data$Date <- as.Date(data$Date)
                subset(data, Date >= input$Dates[1] & Date <= input$Dates[2]
                       & Stock == input$selectStock)
            })

            output$number <- renderText({nrow(datasubset())})
            output$av_adjclose <- renderText({mean(datasubset()$AdjClose)})
            output$av_close <- renderText({mean(datasubset()$Close)})
            output$max_high <- renderText({max(datasubset()$High)})
            output$min_low <- renderText({min(datasubset()$Low)})
            output$av_open <- renderText({mean(datasubset()$Open)})
            output$av_volume <- renderText({mean(datasubset()$Volume)})
            output$plot1 <- renderPlot({ggplot(datasubset(),
                                                    aes(x = Date, y = Close, group = Stock)) +
                                        geom_line() +
                                        geom_smooth(method = loess, se = FALSE, colour = "red") +
                                        theme_classic()})
            output$table1 <- renderDataTable({datasubset()})
}

Now that we have both parts ready we can finally run the app!

Step 5 – Running Shiny app

To start our Shiny app run the following code:

shinyApp(ui = ui, server = server)

Your Shiny app should look like that:

Now you can select dates and stock you want and you will see the data you need.

You can publish your Shiny app at ShinyApps.io or at RStudio Connect or at your own server.

Conclusion

In this article, we showed how we can create a Shiny app for SAS data using SAS9API.
We used retrieve_data  function from rsas9api  package to get data from a SAS dataset in the dataframe format. SAS9API proxy allows you to send different requests to SAS server, including getting and posting data. And with the help of rsas9api  package, you can send requests to all SAS9API endpoints using R language.

To see other examples for SAS9API and R go to Examples > R page.

Feel free to contact us if you have any questions!