0% found this document useful (0 votes)
45 views17 pages

Build Interactive Apps with R Shiny

R Shiny is an R package for building interactive web applications by integrating R with HTML and CSS, allowing users to create apps with minimal web development knowledge. It features a user interface, server logic, and the ability to deploy apps on the web, with reactive elements that reduce server load. The document provides a comprehensive guide on installing R Shiny, structuring apps, creating user interfaces and server functions, and deploying apps using Shinyapps.io.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views17 pages

Build Interactive Apps with R Shiny

R Shiny is an R package for building interactive web applications by integrating R with HTML and CSS, allowing users to create apps with minimal web development knowledge. It features a user interface, server logic, and the ability to deploy apps on the web, with reactive elements that reduce server load. The document provides a comprehensive guide on installing R Shiny, structuring apps, creating user interfaces and server functions, and deploying apps using Shinyapps.io.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Make Interactive Web Apps using R Shiny

What is R Shiny?
Shiny is an R package that allows users to build interactive web apps. This tool creates an HTML
equivalent web app from Shiny code. We integrate native HTML and CSS code with R Shiny functions to
make application presentable. Shiny combines the computational power of R with the interactivity of the
modern web. Shiny creates web apps that are deployed on the web using your server or R Shiny’s hosting
services.

Features of R Shiny:
 Create easy applications with basic or no knowledge of web tools
 Integrate Shiny with native web tools to improve flexibility and productivity
 Pre-built I/O and render functions
 Easy rendering of the application content without multiple reloads
 Feature to add computed (or processed) outputs from R scripts
 Add live reports and visualizations.

How is Shiny different from traditional applications?


Lets us take an example of a weather application, whenever the user refreshes/loads the page or change
any input, it should update the whole page or part of the page using JS. This adds load to the server-side
for processing. Shiny allows the user to isolate or render(or reload) elements in the app which reduces
server load. Scrolling through pages was easy in traditional web applications but was difficult with Shiny
apps. The structure of the code plays the main role in understanding and debugging the code. This feature
is crucial for shiny apps with respect to other applications.

Installing R Shiny
Installing Shiny is like installing any other package in R. Go to R Console and run the below command
to install the Shiny package.

[Link]("shiny")

Once you have installed, load the Shiny package to create Shiny apps.

library(shiny)

Structure of a Shiny app


Shiny consists of 3 components:
1. User Interface
2. Server
3. ShinyApp
1. User Interface Function
User Interface (UI) function defines the layout and appearance of the app. You can add CSS and HTML
tags within the app to make the app more presentable. The function contains all inputs and outputs to be
displayed in the app. Each element (division or tab or menu) inside the app is defined using functions.
These are accessed using a unique id, like HTML elements. Let’s learn further about various functions
used in the app.

Shiny Layout Functions


 headerPanel() add a heading to the app. titlePanel() defines subheading of the app. See the below
image for a better understanding of headerPanel and titlePanel.

 SidebarLayout() defines layout to hold sidebarPanel and mainPanel elements. The layout divides
app screen into sidebar panel and main panel. For example, in the below image, the red rectangle
is the mainPanel area and the black rectangle area vertically is sidebarPanel area.

 wellPanel() defines a container that holds multiple objects app input/output objects in the same
grid.
 tabsetPanel() creates a container to hold tabs. tabPanel() adds tab into the app by defining tab
elements and components. In the below image, the black rectangle is tabsetPanel object and the
red rectangle is the tabPanel object.
 navlistPanel() provides a side menu with links to different tab panels similar
to tabsetPanel() like a Vertical list on the left side of the screen. In the below image, the black
rectangle is navlistPanel object and the red rectangle is the tabPanel object.

Along with Shiny layout functions, you can also add inline CSS to each input widget in the app. The
Shiny app incorporates features of the web technologies along with shiny R features and functions to
enrich the app. Use HTML tags within the Shiny app using tags$<tag name>.

Your layout is ready, It’s time to add widgets into the app. Shiny provides various user input and output
elements for user interaction. Let us discuss a few input and output functions.

I. Shiny Input Functions


Each input widget has a label, Id, other parameters such as choice, value, selected, min, max, etc.

 selectInput() – create a dropdown HTML element.

selectInput("select", h3("Select box"), choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
selected = 1)
 numericInput() – input area to type a number or text.

dateInput("num", "Date input", value = "2014-01-01")
numericInput("num", "Numeric input", value = 1)
textInput("num", "Numeric input", value = "Enter text...")

 radioButtons() – create radio buttons for user input.



radioButtons("radio", h3("Radio buttons"), choices = list("Choice 1" = 1,
"Choice 2" = 2,"Choice 3" = 3),selected = 1)

II. Shiny Output functions


Shiny provides various output functions that display R outputs such as plots, images, tables, etc which
display corresponding R object.

 plotOutput() – display R plot object.



plotOutput"top_batsman")

 tableOutput() – displays output as table.

tableOutput"player_table")
2. Server Function
Server function defines the server-side logic of the Shiny app. It involves creating functions and outputs
that use inputs to produce various kinds of output. Each client (web browser) calls the server function
when it first loads the Shiny app. Each output stores the return value from the render functions.
These functions capture an R expression and do calculations and pre-processing on the expression. Use
the render* function that corresponds to the output you are defining. We access input widgets
using input$[widget-id]. These input variables are reactive values. Any intermediate variables created
using input variables need to be made reactive using reactive({ }). Access the variables using ( ).
render* functions perform the computation inside the server function and store in the output variables.
The output needs to be saved with output$[output variable name]. Each render* function takes a single
argument i.e, an R expression surrounded by braces, { }.

3. ShinyApp Function
shinyApp()function is the heart of the app which
calls UI and server functions to create a Shiny App.

The below image shows the outline of the Shiny app.


Create a Shiny web project
Go to File and Create a New Project in any directory -
> Shiny Web Application -> [Name of Shiny
application Directory]. Enter the name of the directory
and click OK.

Every new Shiny app project will contain a histogram


example to understand the basics of a shiny app. The
histogram app contains a slider followed by a histogram
that updates the output for a change in the slider. Below
is the output of the histogram app.

To run the Shiny app, click on the Run App button on the top right corner of the source pane. The Shiny
app displays a slider widget which takes the number of bins as input and renders the histogram according
to the input.
Create the first Shiny app
You can either create a new project or continue in the
same working directory. In this R Shiny tutorial, we will
create a simple Shiny app to show IPL Statistics. The
dataset used in the app can be downloaded here. The
dataset comprises 2 files, [Link] contains score
deliveries for each ball (in over) batsman, bowler, runs
details and [Link] file contains match details such
as match location, toss, venue & game details. The below
app requires basic knowledge of dplyr and ggplot to
understand the below tutorial.
Follow the below steps to create your first shiny app.

Step 1: Create the outline of a Shiny app.

Clear the existing code except for the function definitions in the app. R file.
In this step, we load the required packages and data. Then, clean and transform the extracted data into the
required format. Add the below code before UI and server function.
Code:
library(shiny)
library(tidyverse)
# Loading Dataset-------------------------------------------------------
deliveries = [Link]("C:UsersCherukuri_SindhuDownloadsdeliveries.csv",
stringsAsFactors = FALSE)
matches = [Link]("C:UsersCherukuri_SindhuDownloadsmatches.csv",
stringsAsFactors = FALSE)
# Cleaning Dataset------------------------------------------------------
names(matches)[1] = "match_id"
IPL = dplyr::inner_join(matches,deliveries)
Explanation:
The first 2 lines load tidyverse and Shiny package. The next 2 lines load datasets deliveries and matches
and store in variables deliveries and matches. The last 2 lines update the column name of
the matches dataset to perform an inner join with the deliveries table. We store the join result in
the IPL variable.

Step 3: Create the layout of Shiny app.


As discussed before, the UI function defines the app’s appearance, widgets, and objects in the Shiny app.
Let’s discuss the same in detail.

Code
ui <- fluidPage(
headerPanel("IPL - Indian Premier League"),
tabsetPanel(
tabPanel(title = "Season",
mainPanel(width = 12,align = "center",
selectInput("season_year","Select Season",choices=unique(sort(matches$season,
decreasing=TRUE)), selected = 2019),
submitButton("Go"),
tags$h3("Players table"),
div(style = "border:1px black solid;width:50%",tableOutput("player_table"))
)),
tabPanel(
title = "Team Wins & Points",
mainPanel(width = 12,align = "center",
tags$h3("Team Wins & Points"),
div(style = "float:left;width:36%;",plotOutput("wins_bar_plot")),
div(style = "float:right;width:64%;",plotOutput("points_bar_plot"))
)
)))

The UI function contains


a headerPanel() or titlePanel() and followed
by tabsetPanel to define multiple tabs in the
app. tabPanel() defines the objects for each tab,
respectively. Each tabPanel() consists of title
and mainPanel(). mainPanel() creates a container of
width 12 i.e full window and align input and output
objects in the center.

Explanation

The app consists of 2 tabs: Season and Team Wins &


Points.

Season tab consists of selectInput(), submit button and


a table. season_year is used to read input from the list of
values. tableOutput() displays table output calculated
on server function. Table player_table is displayed below
button which is defined in server function which shall be
discussed in the next step. Team Wins & Points tab
displays team-wise win and points in respective bar
charts. plotOutput() displays outputs returned from
render* functions. All the output, input functions are
enclosed within a div tag to add inline styling.

Now that we are familiar with ui function, let’s go ahead


with understanding and using server function in our R
Shiny tutorial.

Step 4: Add the server function statements

The server function involves creating functions and


outputs that use user inputs to produce various kinds of
output. The server function is explained step by step
below.
matches_year = reactive({ matches %>% filter(season == input$season_year) })
playoff = reactive({ nth(sort(matches_year()$match_id,decreasing = TRUE),4) })
matches_played = reactive({ matches_year() %>% filter(match_id < playoff()) }) t1 =
reactive({ matches_played() %>% group_by(team1) %>% summarise(count = n()) })
t2 = reactive({ matches_played() %>% group_by(team2) %>% summarise(count = n()) })
wl = reactive({ matches_played() %>% filter(winner != "") %>% group_by(winner) %>%
summarise(no_of_wins = n()) })

wl1=reactive({ matches_played() %>% group_by(winner) %>% summarise(no_of_wins=n()) })


tied = reactive({ matches_played() %>% filter(winner == "") %>% select(team1,team2) })
playertable = reactive({[Link](Teams = t1()$team1,Played=t1()$count+t2()$count,
Wins = wl()$no_of_wins,Points = wl()$no_of_wins*2)})

The above code filter matches played before playoffs each year, and store the result in the
matches_played variable. player_table table contains team-wise match statistics i.e played, wins, and
points. Variables matches_played, player_table, t1, tied, etc are all intermediate reactive values. These
variables need to be accessed using ( ) as shown in the code above. player_table is displayed using
renderTable function. Next, create the output variable to store playertable.

output$player_table = renderTable({ playertable() })

Now lets create bar charts to show wins and points scored by each team in the season. The below code
displays bar charts using ggplot. renderPlot() fetches ggplot object and store the result in
variable wins_bar_plot.The ggplot code is self-explanatory, it involves basic graphics and mapping
functions to edit legend, labels and plot.

output$wins_bar_plot = renderPlot({ ggplot(wl1()[2:9,],aes(winner,no_of_wins,fill=winner))+


geom_bar(stat = "identity")+ theme_classic()+xlab("Teams")+ ylab("Number Of Wins")+theme(
[Link].x=element_text(color="white"),[Link] = "none",[Link]=element_text(
size=14),[Link]=element_rect(colour="white"))+geom_text(aes(x=winner,(no_of_wins+0.6),
label = no_of_wins,size = 7)) })

output$points_bar_plot = renderPlot({ ggplot(playertable(),aes(Teams,Points,fill=Teams))+


geom_bar(stat = "identity",size=3)+theme_classic()+theme([Link].x=element_text(
color = "white"),[Link] = element_text(size = 14),[Link] = element_text(size=14))+
geom_text(aes(Teams,(Points+1),label=Points,size = 7)) })

Step 5: Run the Shiny app.


Click on Run App. With a successful run, your Shiny app will look like below. Any error or warnings
related to the app, it will display these in R Console.

Tab1 — Season
Tab2 — Team Wins & Points

Let’s see how to set up [Link] account to deploy


your Shiny apps.
Let’s see how to set up [Link] account to deploy
your Shiny apps.

III. Set up [Link] Account


Go to [Link] and sign in with your information,
then give a unique account name for the page and save
it. After saving successfully, you will see a detailed
procedure to deploy apps from the R Console. Follow the
below procedure to configure your account in Rstudio.

IV. Step 1. Install rsconnect


[Link]('rsconnect')

V. Step 2. Authorize Account

The rsconnect package must be authorized to your


account using a token and secret. To do this, copy the
whole command as shown below in your dashboard page
in R console. Once you’ve entered the command
successfully in R, I now authorize you to deploy
applications to your [Link] account.
rsconnect::setAccountInfo(name='account
name',token='token', secret="secret")

VI. Step 3. Deploy App

Use the below code to deploy Shiny apps.


library(rsconnect)
rsconnect::deployApp('path/to/your/app')

Once set, you are ready to deploy your shiny apps.


Now that you learned how to create and run Shiny apps,
deploy the app we just created into [Link] as
explained above or click on publish, which is present on
the top right corner of the Shiny app window.
Various packages and libraries used for database
connectivity

Introduction
In a previous post, we had briefly looked at connecting to
databases from R and using dplyr for querying data. In
this new expanded post, we will focus on the following:
 connect to & explore database
 read & write data
 use RStudio SQL script & knitr SQL engine
 query data using dplyr
 visualize data with dbplot
 modeling data with modeldb & tidypredict
 explore RStudio connections pane
 handling credentials
Resources
Below are the links to all the resources related to this
post:
 Slides
 Code & Data
 RStudio Cloud
You can try our free online course Working with
Databases using R if you prefer to learn through self
paced online courses.
Libraries
Before we connect to and explore the local SQLite database, let us take a look at
the R packages we will use in this post.
 DBI a database interface for R
 dbplyr a dplyr backend for databases
 dplyr for querying data
 dbplot & ggplot2 for data visualization
 modeldb & tidypredict for modeling & prediction inside database
 config for handling credentials

# [Link](c("DBI", "dbplyr", "dplyr", "dbplot", "ggplot2", "modeldb",
# "tidypredict", "config"))
library(DBI)
library(dbplyr)
library(dplyr)
library(dbplot)
library(ggplot2)
library(modeldb)
library(tidypredict)
library(config)
If you do not have all the above packages installed, go ahead and install them. In
the R script we are sharing with you, we have commented out the code for
installing the packages. If you are using the RStudio Cloud project, we have
already installed the packages in the project and you can just load them into the R
session using
library()
.
As and when we come to the specific sections where we are using these packages,
they will be reintroduced and we will look at their documentation and explore the
functions we will use.

Relational databases
This section includes packages that provides access to relational databases within
R.
 The DBI package provides a database interface definition for
communication between R and relational database management systems. It’s
worth noting that some packages try to follow this interface definition (DBI-
compliant) but many existing packages don’t.
 The RODBC package provides access to databases through an ODBC
interface. This package is maintained by the R Core Team and depends only
on base R. See alternative odbc package below.
 The odbc package provides a DBI-compliant interface to ODBC drivers.
This package is maintained by RStudio and has a number of package
dependencies. See alternative RODBC package above.
 The RMariaDB package provides a DBI-compliant interface
to MariaDB and MySQL.
 The RMySQL package provides the interface to MySQL. Note that this is
the legacy DBI interface to MySQL and MariaDB based on old code ported
from S-PLUS. A modern MySQL client based on Rcpp is available from the
RMariaDB package we listed above.
 Packages for PostgreSQL, an open-source relational database:
o The RPostgreSQL package and RPostgres package both provide fully
DBI-compliant Rcpp-backed interfaces to PostgreSQL.
o The rpostgis package provides the interface to its spatial
extension PostGIS.
o The RGreenplum provides a fully DBI-compliant interface
to Greenplum, an open-source parallel database on top of
PostgreSQL.
 The ROracle package is a DBI-compliant Oracle database driver based on
the OCI.
 Packages for SQLite, a self-contained, high-reliability, embedded, full-
featured, public-domain, SQL database engine:
o The RSQLite package embeds the SQLite database engine in R and
provides an interface compliant with the DBI package.
o The filehashSQLite package is a simple key-value database using
SQLite as the backend.
o The liteq package provides temporary and permanent message queues
for R, built on top of SQLite.
 The duckdb package provides a DBI interface to DuckDb, an in-process
SQL OLAP database management system.
 The bigrquery package provides the interface to Google BigQuery, Google’s
fully managed, petabyte scale, low cost analytics data warehouse.
 The RDruid package on GitHub provides the interface to Apache Druid, a
high performance analytics data store for event-driven data.
 The RH2 package provides the interface to H2 Database Engine, the Java
SQL database.
 The influxdbr package provides the interface to InfluxDB, a time series
database designed to handle high write and query loads.
 The RPresto package implements a DBI-compliant interface to Presto, an
open source distributed SQL query engine for running interactive analytic
queries against data sources of all sizes ranging from gigabytes to petabytes.
 The RJDBC package is an implementation of R’s DBI interface using JDBC
as a back-end. This allows R to connect to any DBMS that has a JDBC
driver.
 The implyr package provides the back-end for Apache Impala, which
enables low-latency SQL queries on data stored in the Hadoop Distributed
File System (HDFS), Apache HBase, Apache Kudu, Amazon Simple
Storage Service (S3), Microsoft Azure Data Lake Store (ADLS), and Dell
EMC Isilon.
 The dbx package provides intuitive functions for high performance batch
operations and safe inserts/updates/deletes without writing SQL on top
of DBI. It is designed for both research and production environments and
supports multiple database backends such as Postgres, MySQL, MariaDB,
and SQLite.
 The sparklyr package provides provides a dplyr interface to Apache
Spark DataFrames as well as an R interface to Spark’s distributed machine
learning pipelines.
 The Hmisc provides a wrapper function Hmisc::[Link]() that uses
the mdbtools utility to read from Microsoft Access database on Unix-alike
systems.
 The DatabaseConnector provides a DBI compatible interface to various
database platforms using either JDBC or DBI drivers.
Non-relational databases
This section includes packages that provides access to non-relational databases
within R.
 Packages for Redis, an open-source, in-memory data structure store that can
be used as a database, cache and message broker:
o The RcppRedis package provides interface to Redis using hiredis.
o The redux package provides a low-level interface to Redis, allowing
execution of arbitrary Redis commands with almost no interface, and
a high-level generated interface to more than 200 redis commands.
 Packages for Elasticsearch, an open-source, RESTful, distributed search and
analytics engine:
o The elastic package provides a general purpose interface to
Elasticsearch.
o The uptasticsearch package is a Elasticsearch client tailored to data
science workflows.
 The mongolite package provides a high-level, high-
performance MongoDB client based on mongo-c-driver, including support
for aggregation, indexing, map-reduce, streaming, SSL encryption and
SASL authentication.
 The R4CouchDB package provides a collection of functions for basic
database and document management operations in CouchDB.
 Packages for Amazon DynamoDB, a fast, flexible NoSQL database
o The [Link] package on GitHub provides access to inside
from the cloudyr development team.
o The [Link] package provides an interface using the paws suite
of tools.
 The rrocksdb package on GitHub provides access to RocksDB.
Database tools
This section includes packages that provides tools for working and testing with
databases, database table manipulations, etc.
 The MSSQL package extends the functionality of the RODBC package to
work with Microsoft SQL Server databases. Makes it easier to browse the
database and examine individual tables and views.
 The pool package enables the creation of object pools, which make it less
computationally expensive to fetch a new object.
 The DBItest package is a helper that tests DBI back ends for conformity to
the interface.
 The dbplyr package is a dplyr back-end for databases that allows you to
work with remote database tables as if they are in-memory data frames.
Basic features works with any database that has a DBI back-end; more
advanced features require SQL translation to be provided by the package
author.
 The sqldf package provides functionalities to manipulate R Data Frames
Using SQL.
 The pointblank package provides tools to validate data tables in databases
such as PostgreSQL and MySQL.
 The dittodb package provides functionality to test database interactions with
any DBI compliant database backend. It includes functionality to use
fixtures instead of direct database calls during testing as well as
functionality to record those fixtures when interacting with a real database
for later use in tests.
 The tfio package provides the ability to use Apache Ignite, which handles
distributed database management for high-performance computing with in-
memory speed.
 The dbr package on GitHub provides convenient database connections and
queries from R using YAML configuration files and templates.
 The rocker package provides a R6 class interface for handling relational
database connections using DBI as backend. The purpose is having an
intuitive object allowing straightforward handling of SQL databases.
 The SQRL package streamlines exploratory and interactive sessions on
ODBC databases, and allows R code within SQL scripts.
 The octopus package provides an interactive shiny application for database
management to view tables and schemas, upload files, send queries, and
more.

CRAN packages
C DBI, odbc, RODBC.
or
e:
Re bigrquery, DatabaseConnector, DBItest, dbplyr, dbx, dittodb, dplyr, duckdb, el
gu astic, filehashSQLite, Hmisc, implyr, influxdbr, liteq, mongolite, MSSQL, octo
la pus, paws, [Link], pointblank, pool, R4CouchDB, R6, RcppRedis, redu
r: x, RGreenplum, RH2, RJDBC, RMariaDB, RMySQL, rocker, ROracle, rpostgi
s, RPostgres, RPostgreSQL, RPresto, RSQLite, sparklyr, sqldf, SQRL, tfio, upt
asticsearch.

You might also like