32,36 €
Analyze, communicate, and design your own sophisticated and interactive web applications using the R (v 3.4) Shiny (1.1.0) package
Key Features
Book Description
Web Application Development with R Using Shiny helps you become familiar with the complete R Shiny package. The book starts with a quick overview of R and its fundamentals, followed by an exploration of the fundamentals of Shiny and some of the things that it can help you do. You'll learn about the wide range of widgets and functions within Shiny and how they fit together to make an attractive and easy to use application.
Once you have understood the basics, you'll move on to studying more advanced UI features, including how to style apps in detail using the Bootstrap framework or and Shiny's inbuilt layout functions.
You'll learn about enhancing Shiny with JavaScript, ranging from adding simple interactivity with JavaScript right through to using JavaScript to enhance the reactivity between your app and the UI.
You'll learn more advanced Shiny features of Shiny, such as uploading and downloading data and reports, as well as how to interact with tables and link reactive outputs. Lastly, you'll learn how to deploy Shiny applications over the internet, as well as and how to handle storage and data persistence within Shiny applications, including the use of relational databases.
By the end of this book, you'll be ready to create responsive, interactive web applications using the complete R (v 3.4) Shiny (1.1.0) suite.
What you will learn
Who this book is for
Web Application Development with R Using Shiny is for you if you are interested in creating compelling web applications and interactive data visualization over the web using Shiny. Programming experience with R is required.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 264
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Acquisition Editor: Devanshi DoshiContent Development Editor: Aishwarya GawankarTechnical Editor: Rutuja VazeCopy Editor: Safis EditingProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer: Pratik ShirodkarGraphics: Alishon MendonsaProduction Coordinator: Arvindkumar Gupta
First published: October 2013 Second published: January 2016 Third edition: September 2018
Production reference: 1260918
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78899-312-8
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Chris Beeley has been using R and other open source software for ten years to better capture, analyze, and visualize data in the healthcare sector in the UK. He is the author of Web Application Development with R Using Shiny. He works full-time, developing software to store, collate, and present questionnaire data using open technologies (MySQL, PHP, R, and Shiny), with a particular emphasis on using the web and Shiny to produce simple and attractive data summaries. Chris is working hard to increase the use of R and Shiny, both within his own organization and throughout the rest of the healthcare sector, as well to enable his organization to better use a variety of other data science tools. Chris has also delivered talks about Shiny all over the country.
Shitalkumar R. Sukhdeve is a senior data scientist at PT Smartfren Telecom Tbk, Jakarta, Indonesia. On his career journey, he has worked with Reliance Jio as a data scientist, entrepreneur, and corporate trainer. He has trained over 1,000 professionals and students and has delivered over 200 lectures on R and machine learning. Research and development in AI-driven self-optimizing networks, predictive maintenance, optimal network quality, anomaly detection, and customer experience management for 4G LTE networks are all areas of interest to Shitalkumar. He is very experienced with R, Spark, R Shiny, H2O, Python, KNIME, the Hadoop ecosystem, MapReduce, Hive, and configuring the open source R Shiny server for machine learning models and dashboard deployment.
Abhinav Agrawal has more than 13 years' IT experience and has worked with top consulting firms and US financial institutions. His expertise lies in the banking and financial services domain and he is a seasoned project/program management professional with a passion for data analytics, machine learning, artificial intelligence, robotics process automation, digital transformation, and emerging digital payments solutions. He started using R and Shiny in 2014 to develop web-based analytics solutions for clients. He works as a program manager and is a freelance R instructor and R Shiny consultant. In his spare time, he loves to mentor data science students, make data analytics-related instructional videos on YouTube, and share knowledge with the community.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Web Application Development with R Using Shiny Third Edition
www.PacktPub.com
Why subscribe?
Packt.com
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Beginning R and Shiny
Installing R
The R console
Code editors and IDEs
Learning R
Getting help
Loading data
Data types and structures
Dataframes, lists, arrays, and matrices
Variable types
Functions
Objects
Base graphics and ggplot2
Bar chart
Line chart
Introduction to the tidyverse
Ceci n'est pas une pipe
Gapminder
A simple Shiny-enabled line plot
Installing Shiny and running the examples
Summary
Shiny First Steps
Types of Shiny application
Interactive Shiny documents in RMarkdown
A minimal example of a full Shiny application
The ui.R of the minimal example
A note on HTML helper functions
The finished interface
The server.R of the minimal example
The program structure
An optional exercise
Embedding applications in documents
Widget types
The Gapminder application
The UI
Data processing
Reactive objects
Outputs
Text summary
Trend graphs
A map using leaflet
Advanced layout features
Summary
Integrating Shiny with HTML
Running the applications and code
Shiny and HTML
Custom HTML links in Shiny
ui.R
server.R
A minimal HTML interface
index.html
server.R
Including a Shiny app on a web page
HTML templates
Inline template code
server.R
ui.R and template.html
Defining code in the ui.R file
ui.R
Take a step back and rewind
Exercise
Debugging
Bootstrap 3 and Shiny
Summary
Mastering Shiny's UI Functions
Shiny's layout functions
Simple
Complete
Do it yourself
Combining layout functions
Streamlining the UI by hiding elements
Naming tabPanel elements
Beautiful tables with DataTable
Reactive user interfaces
The reactive user interface example – server.R
The reactive user interface example – ui.R
Progress bars
Progress bar with shinycssloaders
Modals
Alternative Shiny designs
Summary
Easy JavaScript and Custom JavaScript Functions
JavaScript and Shiny
Example 1 – reading and writing the DOM
ui.R
appendText.js
Example 2 – sending messages between client and server
ui.R
server.R
dropdownDepend.js
Shinyjs
Extendshinyjs
ui.R
server.R
JavaScript
Responding to events in JavaScript
htmlwidgets
Dygraphs
rCharts
d3heatmap
threejs
Summary
Dashboards
Applications in this chapter
Flexdashboards
Sidebar application with extra styling
Adding icons to your UI
Using shinythemes
Using the grid layout
ui.R
Full dashboard
Notifications
Info boxes
ui.R
Google Charts gauge
Resizing the Google chart
ui.R
Summary
Power Shiny
Animation
Reading client information and GET requests in Shiny
Custom interfaces from GET strings
Downloading graphics and reports
Downloadable reports with knitr
Downloading and uploading data
Bookmarking
Bookmarking state
Encoding the state into a URL
Single-file application
Multiple-file application
Bookmarking by saving the state to the server
Interactive plots
Interactive tables
Row selection
Column selection
Cell Selection
Linking interactive widgets
Shiny gadgets
Adding a password
Summary
Code Patterns in Shiny Applications
Reactivity in RShiny
A closer look at reactivity
Controlling specific input with the isolate() function
Running reactive functions over time (execution scheduling)
Event-handling using observeEvent and eventReactive
Functions and modules
Shinytest
Debugging
Handling errors (including validate() and req())
Validate
Handling missing input with req()
Profiling R code
Debounce and throttle
Summary
Persistent Storage and Sharing Shiny Applications
Sharing over GitHub
An introduction to Git
Using Git and GitHub within Rstudio
Projects in RStudio (h3)
Sharing applications using Git
Sharing using .zip and .tar
Sharing with the world
Shinyapps.io
Shinyapps.io without RStudio
Shiny server
Running Shiny app on Amazon AWS
Scoping, loading, and reusing data in Shiny applications
Temporary data input/output
Persistent data storage
Database using Dplyr, DBI, and POOL
SQL Injection
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
With this book, you will be able to harness the graphical and statistical power of R and rapidly develop interactive and engaging user interfaces using the superb Shiny package, which makes programming for user interaction simple. R is a highly flexible and powerful tool used for analyzing and visualizing data. Shiny is the perfect companion to R, making it quick and simple to share analysis and graphics from R for users to then interact with and query over the web. Let Shiny do the hard work while you spend your time generating content and styling, rather than writing code to handle user inputs. This book is full of practical examples and shows you how to write cutting-edge interactive content for the web, right from a minimal example all the way to fully styled and extensible applications.
This book includes an introduction to Shiny and R and takes you all the way to advanced functions in Shiny as well as using Shiny in conjunction with HTML, CSS, and JavaScript to produce attractive and highly interactive applications quickly and easily. It also includes a detailed look at other packages available for R, which can be used in conjunction with Shiny to produce dashboards, maps, advanced D3 graphics, and much more.
This book is for anybody who wants to produce interactive data summaries over the web, whether you want to share them with a few colleagues or the whole world.
Chapter 1, Beginning R and Shiny, runs through the basics of statistical graphics, data input, and analysis with R. We also discuss data structures and programming basics in R in order to give you a thorough grounding in R before we look at Shiny.
Chapter 2, Shiny First Steps, helps you build your first Shiny application. We begin by simply adding interactive content to a document written in Markdown; and then delve deeper into Shiny, building a very primitive and minimal example; and finally, we'll look at more complex applications and the inputs and outputs necessary to build them.
Chapter 3, Integrating Shiny with HTML, covers how Shiny works with existing web content in HTML and CSS. We discuss the Shiny helper functions that allow you to add a custom HTML to a standard Shiny application and how to build a minimal example of a Shiny application in your own raw HTML with Shiny running in the background. We'll also get into the use of HTML templates, which make integrating Shiny with HTML easy.
Chapter 4, Mastering Shiny's UI Functions, describes all the different ways that Shiny offers to help you achieve the layout and appearance that you want your application to have. It discusses how to show and hide elements of the interface, as well as how to make the interface react to the state of the application. Producing attractive data tables is discussed, as well as how to give your users messages with progress bars and modals.
Chapter 5, Easy JavaScript and Custom JavaScript Functions, covers using JavaScript with Shiny, right from adding simple JavaScript right on the page to enhance a program's appearance or functionality, to sending messages to and from the client's browser using messages to and from JavaScript. The use of the shinyjs and htmlwidgets packages is also discussed, which further add to your ability to add custom or canned JavaScript to a Shiny application.
Chapter 6, Dashboards, includes a couple of different types of Shiny dashboard, and describes how to make attractive Shiny dashboards, using color, icons, and a wide range of inputs and outputs, as well as how to lay them out using the very flexible layout functions, which can be accessed with a Shiny dashboard.
Chapter 7, Power Shiny, includes many powerful features of Shiny, such as animating plots, reading client information, and GET requests in Shiny. We will go through graphics and report generation and how to download them using knitr. Downloading and uploading is also an interesting part of any application, and we'll take a look at it in Shiny with some examples. Bookmarking the state of the application is an add-on to regenerate the output on the application. We will see a demonstration of fast application development using widgets and gadgets. At the end of the chapter, we will see how to authenticate the application using a password.
Chapter 8, Code Patterns in Shiny Applications, covers the coding patterns available in Shiny. We will discuss reactivity in R Shiny, controlling specific input with the isolate() function, running reactive functions over time, event handling using the observeEvent functions and the Shinytest modules, debugging, handling errors (including validate() and req()), profiling R code, debounce, and throttle.
Chapter 9, Persistent Storage and Sharing Shiny Applications, will explore how to keep your code on GitHub. This chapter will include an introduction to GitHub and how to integrate Git with RStudio. We will also learn how to share your reports and a live application with Shinyapps.io. This chapter will also focus on the deployment options available, such as Shiny Server and running Shiny in AWS. We will go through some of the concepts that are vital for developing a good Shiny application, such as scoping, loading, and reusing data in Shiny applications. We'll also look at temporary data input/output, permanent data functions, databases, SQL injection, and databases with the pool package.
No previous experience with R, Shiny, HTML, or CSS is required to use this book, although you should possess some previous experience with programming in a different language. This book can be used with the Windows, macOS, or Linux operating systems. It requires the installation of R as well as several user-contributed packages within R. R and its associated packages are all available for free. The RStudio IDE is recommended because it simplifies some of the tasks covered in this book, but is not essential. Again, this software is available free of charge.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Web-Application-Development-with-R-Using-Shiny-third-edition. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781788993128_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
R is free and open source, and is the pre-eminent tool for statisticians and data scientists. It has more than 6,000 user-contributed packages, which help users working in fields as diverse as chemistry, biology, physics, finance, psychology, and medical science. R's extremely powerful and flexible statistical graphics greatly help these users in their work.
In recent years, R has become more and more popular, and there are an increasing number of packages for R that make cleaning, analyzing, and presenting data on the web easy for everybody. The Shiny package in particular makes it incredibly easy to deliver interactive data summaries and queries to end users through any modern web browser. You're reading this book because you want to use these powerful and flexible tools for your own content.
This book will show you how, right from when you just start with R, you can build your own interfaces with Shiny and integrate them with your own websites. In this chapter, we're going to cover the following topics:
Downloading and installing R
Choosing a code-editing environment/IDE
Looking at the power of R
Learning about how RStudio and contributed packages can make writing code, managing projects, and working with data easier
Installing Shiny and running the examples
How to use some of Shiny's awesome applications, and some of the elements of the Shiny application that we will build over the course of this book
R is a big subject, and this is a whistle-stop tour, so if you get a little lost along the way, don't worry. This chapter is really all about showing you what's out there, and will both encourage you to delve deeper into the bits that interest you and show you places you can go for help if you want to learn more on a particular subject.
R is available for Windows, Mac OS X, and Linux at cran.r-project.org. The source code is also available at the same address. It is also included in many Linux package management systems; Linux users are advised to check before downloading from the web. Details on installing from source or binary for Windows, Mac OS X, and Linux are all available at cran.r-project.org/doc/manuals/R-admin.html.
Windows and Mac OS X users can run the R application to launch the R console. Linux and Mac OS X users can also run the R console straight from the Terminal by typing R.
In either case, the R console itself will look something like the following screenshot:
R will respond to your commands right from the Terminal. Let's have a go. Run the following command in the R console:
> 2 + 2
[1] 4
The [1] phrase tells you that R returned one result, in this case, 4. The following command shows you how to print Hello world:
> print("Hello world!")
[1] "Hello world!"
The following command shows the multiples of pi:
> 1:10 * pi
[1] 3.141593 6.283185 9.424778 12.566371 15.707963 18.849556
[7] 21.991149 25.132741 28.274334 31.415927
This example illustrates vector-based programming in R. The 1:10 phrase generates the numbers 1:10 as a vector, and each is then multiplied by pi, which returns another vector, the elements each being pi times larger than the original. Operating on vectors is an important part of writing simple and efficient R code. As you can see, R again indexes the values it returns at the console, with the seventh value being 21.99.
One of the big strengths of using R is the graphics capability, which is excellent, even in a vanilla installation of R (these graphics are referred to as the base graphics because they ship with R). When adding packages such as ggplot2 and some of the JavaScript-based packages, R becomes a graphical tour de force, whether producing statistical, mathematical, or topographical figures, or indeed any other type of graphical output. To get a flavor of the power of the base graphics, simply type the following in the Console and see the types of plots that can be made using R:
> demo(graphics)
You can also type the following command:
> demo(persp)
There will be more on ggplot2 and base graphics later in the chapter.
Enjoy! There are many more examples of R graphics at r-graph-gallery.com.
The Windows and OS X versions of R both come with built-in code editors, which allow code to be edited, saved, and sent to the R console. It's hard to recommend that you use this because it is rather primitive. Most users would be best served by RStudio (found at rstudio.com/), which includes project management and version control (including support for Git, which is covered in Chapter 9, Persistent Storage and Sharing Shiny Applications), the viewing of data and graphics, code completion, package management, and many other features. The following is an illustrative screenshot of an RStudio session:
As can be seen, in the top-left corner, there is the code-editing pane (with syntax highlighting). Moving clockwise from there will take you to the environment pane (in which you can see the different objects that are loaded into the session), which is the viewing pane containing various options such as Files, Plots, Build, Help, and finally, at the bottom left, the Console. In the middle, there is one of the most useful features of RStudio, the ability to view dataframes. This view can be created by clicking a dataframe in the Environment panel at the top right. This function also enables sorting and filtering by column.
However, if you already use an IDE for other types of code, it is quite likely that R can be well integrated into it. Examples of IDEs with good R integration include the following:
Emacs with the Emacs Speaks Statistics plugin
Vim with the Vim-R plugin
Eclipse with the StatET plugin
There are almost as many uses for R as there are people using it. It is not possible that your specific needs will be covered in this book. However, you probably want to use R to process, query, and visualize data, such as sales figures, satisfaction surveys, concurrent users, sporting results, or whatever types of data your organization processes. For now, let's just take a look at the basics.
There are many books and online materials that cover all aspects of R. The name R can make it difficult to come up with useful web search hits (substituting CRAN for R can sometimes help); nonetheless, searching for R tutorial brings up useful results. Some useful resources include the following:
An excellent introduction to syntax and data structures in R (at
goo.gl/M0RQ5z
)
Videos on using R from Google (at
goo.gl/A3uRsh
)
Swirl (at
swirlstats.com
)
Quick-R (at
statmethods.net
)
At the R console, the code phrase ?functionname can be used to show the help file for a function. For example, ?help brings up help materials, and using ??help will bring up a list of potentially relevant functions from installed packages.
Subscribing to and asking questions on the R-help mailing list at stat.ethz.ch/mailman/listinfo/r-help allows you to communicate with some of the leading figures in the R community, as well as many other talented enthusiasts. Read the posting guide and do your research before you ask any questions, because it's a busy and sometimes unforgiving list.
There are two Stack Exchange communities that can provide further help at stats.stackexchange.com/ (for questions about statistics and visualization with R) and stackoverflow.com/ (for questions about programming with R).
There are many ways to learn R and related subjects online; RStudio has a very useful list on their website at goo.gl/8tX7FP.
There are many data types and structures of data within R. The following topics summarize some of the main types and structures that you will use when building Shiny applications.
Dataframes have several important features that make them useful for data analysis:
Rectangular data structures, with the typical use being cases (for example, the days in one month) listed down the rows and variables (page views, unique visitors, or referrers) listed along the columns
A mix of data types is supported. A typical data frame might include variables containing dates, numbers (integers or floats), and text
With subsetting and variable extraction, R provides a lot of built-in functionality to select rows and variables within a dataframe
Many functions include a data argument, which makes it very simple to pass dataframes into functions and process only the variables and cases that are relevant, which makes for cleaner and simpler code
