Shiny: Difference between revisions
Line 340: | Line 340: | ||
) #close navbar page | ) #close navbar page | ||
output$fitLasso <- renderText({ }) | server <- function(input, output, session) { | ||
output$fitLasso2 <- renderPrint({ }) | output$fitLasso <- renderText({ }) | ||
output$fitLasso2 <- renderPrint({ }) | |||
} | |||
shinyApp(ui, server) | |||
</pre> | </pre> | ||
Revision as of 15:34, 15 September 2022
Preliminary
The following is what we see on a browser after we run an example from shiny package. See http://rstudio.github.com/shiny/tutorial/#hello-shiny. Note that the R session needs to be on; i.e. R command prompt will not be returned unless we press Ctrl+C or ESC.
More shiny examples can be found on https://github.com/rstudio/shiny-examples 188 shiny-examples (note this is not what runExample("08_html") used. runExample() used local files that contain only 11 examples). The local directory is /Library/Frameworks/R.framework/Versions/4.2/Resources/library/shiny/ for R 4.2.x on macOS.
shiny depends on websockets, caTools, bitops, digest packages.
Q & A:
- Tutorial: http://wch.github.io/shiny/tutorial/
- Layout: http://shiny.rstudio.com/articles/layout-guide.html
Q: If we run runExample('01_hello') in Rserve from an R client, we can continue our work in R client without losing the functionality of the GUI from shiny. Question: how do we kill the job?- If I run the example "01_hello", the browser only shows the control but not graph on Firefox? A: Use Chrome or Opera as the default browser.
- Q: How difficult to put the code in Gist:github? A: Just create an account. Do not even need to create a repository. Just go to http://gist.github.com and create a new gist. The new gist can be secret or public. A secret gist can not be edited again after it is created although it works fine when it was used in runGist() function.
Resources
- Mastering shiny Hadley Wickham
- Interactive web-based data visualization with R, plotly, and shiny Carson Sievert 2019
- Shiny Production with AWS Book by Matt Dancho
- The Best Resources for Learning Shiny App Development
- Top 7 Best R Shiny Books and Courses That Are Completely Free
Deploy to run locally
Follow the instruction here, we can do as following (Tested on Windows OS)
- Create a desktop shortcut with target "C:\Program Files\R\R-3.0.2\bin\R.exe" -e "shiny::runExample('01_hello')" . We can name the shortcut as we like, e.g. R+shiny
- Double click the shortcut. The Windows Firewall will be popped up and say it block some features of the program. It does not matter if we choose Allow access or Cancel.
- Look at the command prompt window (black background console window), it will say something like
Listening on port 7510
at the last line of the console. - Open your browser (Chrome or Firefox works), and type the address http://localhost:7510. You will see something magic happen.
- If we don't want to play with it, we can close the browser and close the command console (hit 'x')too.
rmarkdown::run() instead of rmarkdown::render()
Use rmarkdown::run("XXX.Rmd") file. If you use the render() function, you will receive an error "Error: path for html_dependency not provided Execution".
RInno
Installs shiny apps packaged as stand-alone Electron apps using Inno Setup, an open source software that builds installers for Windows programs only.
Deploy on cloud
https://www.r-bloggers.com/deploying-r-rstudio-and-shiny-applications-on-unbuntu-server/
Shiny server series part 1: setting up. It includes setting up A- and CNAME records on DigitalOcean.
Deploy on shinyapps.io
About the account
- Getting started with shinyapps.io page and Dashboard page.
- Limitations of the free account (5 applications, 25 active hours per month) on shinyapps.io.
- How Many Shiny Apps Can You Host for Free?
- Deploy to Shinyapps.io from Github Actions
- Push Button Publishing for Shiny Apps
Shinyapps.io can accept google account to sign up.
https://taichimd.shinyapps.io/stock/ (quantmod, ggplot2, reshape2, magrittr, rvest packages were used)https://taichimd.shinyapps.io/tspgov (ggplot2, reshape2, magrittr, rvest, plotly), Performance- https://shiny.taichimd.us/shiny-examples.html 188 shiny examples. source code for this HTML
- https://taichimd.shinyapps.io/Lasso_Simulation/ Lasso with simulated data
- https://taichimd.shinyapps.io/shinysurvival/ Kaplan-Meier curves plotter
- https://taichimd.shinyapps.io/cran-downloads/ (a backup copy of hadley shiny app). Some packages to test:
- ggpubr, survminer, GGally, glmnet, survAUC
- glmnet, SGL, MSGLasso, grplasso, biospear
- dockerfiler, stevedore, babelwhale, liftr
Note:
- The R packages our shiny app uses will be automatically downloaded by shinyapps.io service. See the package dependencies section on http://shiny.rstudio.com/articles/shinyapps.html and Using your R packages in the cloud.
- Default System Packages.
- Two commands are needed to upload an app:
- rsconnect::setAccountInfo() [the full command is copied from account's token page.
- rsconnect::deployApp() [assume we are in the right working directory]. If the machine contains several accounts, we can use deployApp(account = "XXXX") to specify the account we want to deploy the app. After successful deployment, the browser will open the URL for our app.
- After we run rsconnect() command to deploy our apps, a new subfolder rsconnect will be created under our app folder. I add this folder to .gitignore file. But it seems this file/folder does not contain any secret information. So not worry.
- The rsconnect stores account information. If we get the app from another account make sure to delete this subfolder before we run rsconnect::deployApp(); otherwise we will get an error message Error: HTTP 403 .... Forbidden'; see I can't deploy my app with a name that was used in a previous deleted app.
- For the shiny apps we uploaded to shinyapps.io, we can download them back. The download bundle will also include packrat subfolder (packrat.lock file and desc subfolder). See R packages → packrat for more about packrat.
Shiny server installation
Each app directory needs to be copied to /srv/shiny-server/ (which links to /opt/shiny-server/) directory using sudo.
The default port is 3838. That is, the remote computer can access the website using http://xxx.xxx.x.xx:3838/AppName.
Release
Shiny Server 1.5.16 Update 2021-01-03
Ubuntu & firewall
In my case, I need to modify the firewall to allow traffic through to Shiny Server sudo ufw allow 3838. See How to Set Up Shiny Server on Ubuntu 16.04. The tutorial also covers Securing Shiny Server with a Reverse Proxy and SSL Certificate.
RHEL/CentOS 7
https://www.vultr.com/docs/how-to-install-shiny-server-on-centos-7
Raspberry Pi
- Automatically installing Shiny and RStudio server on Raspberry Pi OS with Ansible 2021-01-13
- http://atceiling.blogspot.com/2017/12/raspberry-pi-r-languager-shiny-server.html
R
sudo nano /etc/apt/sources.list # deb http://archive.raspbian.org/raspbian/ stretch main sudo apt-get update sudo apt-get install r-base r-base-core r-base-dev
Shiny-server
sudo apt-get install cmake sudo su - -c "R -e \"install.packages('shiny', repos='http://cran.rstudio.com/')\"" git clone https://github.com/rstudio/shiny-server.git cd shiny-server mkdir tmp cd tmp DIR=`pwd` PATH=$DIR/../bin:$PATH PYTHON=`which python` $PYTHON --version cmake -DCMAKE_INSTALL_PREFIX=/usr/local -DPYTHON="$PYTHON" ../ make mkdir ../build (cd .. && ./bin/npm --python="$PYTHON" install) (cd .. && ./bin/node ./ext/node/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js --python="$PYTHON" rebuild) sudo make install sudo ln -s /usr/local/shiny-server/bin/shiny-server /usr/bin/shiny-server sudo useradd -r -m shiny sudo mkdir -p /var/log/shiny-server sudo mkdir -p /srv/shiny-server sudo mkdir -p /var/lib/shiny-server sudo chown shiny /var/log/shiny-server sudo mkdir -p /etc/shiny-server cd /etc/shiny-server/ sudo wget http://withr.me/misc/shiny-server.conf sudo shiny-server http://192.168.X.XXX:3838
建立 server.R 及 ui.R 程式
cd /srv/shiny-server mkdir hello_shiny cd hello_shiny # 分別建立 server.R 及 ui.R
Running shiny server as non-root: run_as
- https://stackoverflow.com/questions/36201019/run-shiny-server-as-non-root
- https://support.rstudio.com/hc/en-us/articles/219044787-Root-requirements-for-Shiny-Server
- http://docs.rstudio.com/shiny-server/#run_as
Google analytics
https://docs.rstudio.com/shiny-server/#google-analytics
Reverse proxy: Deploy your own shiny server
- http://qualityandinnovation.com/2015/12/09/deploying-your-very-own-shiny-server/
- Set up Apache(Nginx or another webserver) to act as a proxy to Shiny Server
- Setting up RStudio Server, Shiny Server and PostgreSQL
- When used with cloudflare, we should disable HTTP proxy (CDN) and use DNS only.
- How to make your home Shiny or Rstudio Server accessible from the public internet
Shiny https: Securing Shiny Open Source with SSL
Securing Shiny Server with Caddy
Shiny for Python
How to run an R shiny app
- Building Shiny apps – an interactive tutorial by Dean Attali
- Three ways
- Click "Run App" in RStudio
- Call shiny::runApp("~/Directory") in your R console
- R -e "shiny::runApp('~/shinyapp')" from a terminal
- An example of "app.R". Edit a table via the "DT" package.
- Turn a shiny application into a tablet or desktop app
shinyuieditor
shinyuieditor package
Shiny UI Prototype Builder
designer package
How to Build a Data Analysis App in R Shiny
How to Build a Data Analysis App in R Shiny
Landing page
- We can create an HTML file in /srv/shiny-server directory as the landing page where each app is under a sub-directory.
- R Shiny Apps by Sharon Machlis
- shinyLP package. Bootstrap Landing Home Pages for Shiny Applications
- Host a directory of applications from Shiny Server Professional v1.5.17 Administrator's Guide
The R Shiny packages you need for your web apps
http://enhancedatascience.com/2017/07/10/the-packages-you-need-for-your-r-shiny-application/
Other web apps
Ten simple rules for researchers who want to develop web apps
Shiny + Docker
- See this post. It uses the gui of Docker called Kitematic.
- https://hub.docker.com/r/rocker/shiny/ Don't run R Shiny as a non-root user.
- Shiny Server on Docker: CentOS 7 Edition
- https://github.com/rocker-org/shiny
- https://www.r-bloggers.com/dockerizing-a-shiny-app/
- https://github.com/keberwein/docker_shiny-server_centos7 (Shiny + RStudio servers)
- How To Dockerize ShinyApps + renv package
- Deploying an R Shiny App With Docker
- Running a shiny app in a docker container
- Dockerized Shiny Apps with Dependencies. renv
- Host Shiny Apps with Docker
- Using systemd to Run Shiny Apps
- Running Shiny Server in Docker
- Shiny Apps with Docker Compose, Part 1: Development
- UCSCXenaShiny: An R package for interactively exploring UCSC Xena
Dashboard
shinydashboard
- http://rstudio.github.io/shinydashboard/
- Dashboards made easy
- Using Shiny with Scheduled and Streaming Data
flexdashboard
- The output can be a static HTML file or a dynamic HTML (using shiny, highcharter, viridisLite, ...)
- https://rmarkdown.rstudio.com/flexdashboard/
- Introducing flexdashboards. The gauge component is cool.
- Real example containing gauges https://gallery.shinyapps.io/cran-gauge/
- Automated Dashboard for Classification Neural Network in R
- Automated Dashboard with various correlation visualizations in R
- Speeding up R Plotly web apps - R x Javascript part I
shinyalert: create pretty popup messages (modals) in Shiny
shinyjs
Dash bio for R
shinytheme
bootstraplib
How to use bootstraplib's Live Theme Previewer to customize Shiny apps?
shiny + databases
tags, hyperlinks
- https://stackoverflow.com/questions/42047422/create-url-hyperlink-in-r-shiny
- Customize your UI with HTML
dates
- https://stackoverflow.com/questions/22834778/r-shiny-daterangeinput-format
- http://www.noamross.net/blog/2014/2/10/using-times-and-dates-in-r---presentation-code.html
websocket
CentOS
- https://www.vultr.com/docs/how-to-install-shiny-server-on-centos-7
- https://github.com/rstudio/shiny-server/wiki/CentOS-step-by-step-Installation-Instructions
- http://blog.supstat.com/2014/05/install-rstudio-server-on-centos6-5/
Gallery
git clone https://github.com/rstudio/shiny-examples.git shiny::runApp("~/github/shiny-examples/018-datatable-options/")
- Shiny User Showcase
- Introducing Shiny App Stories
- http://www.showmeshiny.com/
- Example of using googleVis: http://shinyeoda.cloudapp.net/
- Integrate with Javascript: https://github.com/wch/shiny-jsdemo and https://github.com/trestletech/ShinyDash-Sample
- interactiveDisplay (Bioconductor package, there is a STOP Application button too): http://www.bioconductor.org/packages/release/bioc/html/interactiveDisplay.html
- Party vote characteristics at the New Zealand General Election 2014, More things with the New Zealand Election Study
- geneSurv : An interactive web-based tool for survival analysis in genomics research. The paper and the source code.
- gene2drug
- Stock
- http://shiny.rstudio.com/tutorial/written-tutorial/lesson6/
- Stock Closing Price History.
- Multiple stocks.
- google (flash is required, not accurate eg DOW). msn (Nice).
- yahoo (French only).
- S&P500 Dashboard, Github source code
Persistent data storage in Shiny apps
http://deanattali.com/blog/shiny-persistent-data-storage/
multiple outputs to mainPanel
https://stackoverflow.com/a/27383312. Or use fluidRow() to expand the output in one tabPanel.
ui <- navbarPage("My App", tabPanel("Lasso", sidebarLayout( sidebarPanel( ... ), mainPanel( tabsetPanel( tabPanel("CV plot", plotOutput("plotLasso")), tabPanel("Lasso fitting", #verbatimTextOutput("fitLasso")) fluidRow( column(12, TextOutput("fitLasso", inline=T)), column(12, verbatimTextOutput("fitLasso2")) )) ) ) # close mainPanel ) # close sidebarLayout ), # close tabPanel Lasso ) #close navbar page server <- function(input, output, session) { output$fitLasso <- renderText({ }) output$fitLasso2 <- renderPrint({ }) } shinyApp(ui, server)
How to get the selected Tab-ID in a navbarPage with modules
HTML
- Customize your UI with HTML
# adding the new div tag to the sidebar tags$div(class="header", checked=NA, tags$p("Ready to take the Shiny tutorial? If so"), tags$a(href="shiny.rstudio.com/tutorial", "Click Here!")
- Build your entire UI with HTML. This seems to be a more complicated approach at first glance.
<application-dir> |-- app.R |-- www |-- index.html
and "app.R"
# ui is defined in the HTML file server <- function(input, output) { } shinyApp(ui = htmlTemplate("www/index.html"), server)
- HTML templates
- Shiny HTML Tags Glossary
Conditional input
Upload a file/files
- https://shiny.rstudio.com/articles/upload.html. fileInput(), renderTable(), tableOutput()
- how to upload and access multiple CSV files in R Shiny, source code. renderTable(), renderPrint(), renderUI().
- demo upload a zip file and unzip it to local machine. Source code. observeEvent()
- CASAS: Cancer Survival Analysis Suite, a web based application
- fileInput "accept" not filtering options. The RStudio built in web browser does not use the accept attribute. It will always show "All Files (*)" if you view your shiny app through RStudio. The RStudio built in web browser does not use the accept attribute. It will always show "All Files (*)" if you view your shiny app through RStudio.
reactive
- Lesson 4 Display reactive output
- Reactivity - An overview
- ?reactive, Lesson 6 Use reactive expressions
- 3 Basic reactivity from Mastering Shiny
- Shiny Reactivity Tricks, pt. II: Reactives Factories
actionButton and isolate
- https://shiny.rstudio.com/articles/isolation.html
- 049-isolate-demo
- It seems isolate() will always run the code one time. So consider eventReactive() or observeEvent() instead.
actionButton and eventReactive*
R Shiny App Tutorial | eventReactive() demo | Create dependency on actionButton
actionButton, observeEvent and reactiveValues
- ?reactiveValues
- Based on the following 2 examples. It seems
- reactiveValues() and observeEvent() work together.
- reactiveValues() will create a global variable and its value will be changed based on an actionButton.
- the effect of observeEvent() + reactiveValues() is similar to eventReactive() if we don't consider the situation that the new value depends on the old value.
- reactiveValues example
text_reactive <- reactiveValues( text = "No text has been submitted yet." ) observeEvent(input$submit, { text_reactive$text <- input$user_text }) output$text <- renderText({ text_reactive$text })
eventReactive() way:
text <- eventReactive(input$submit, { input$user_text }) output$text <- renderText({ text() })
- reactiveValues() in R Shiny - Example 1 - A counter (video)
counter <- reactiveValues(countervalue = 0) observeEvent(input$add1, counter$countervalue <- counter$countervalue + 1 output$counter <- renderText({ counter$countervalue })
The following code will break (Error in : C stack usage 7969216 is too close to the limit). So this is the case eventReactive() can't replace reactiveValues()!
countervalue <- eventReactive(input$add1, { countervalue() + 1 }) output$counter <- renderText({ countervalue() })
Dynamic UI
- Build a dynamic UI that reacts to user input. reactive(), observeEvent()
- Dynamically generated user interface components
- Dynamic UI in Shiny (incl. demo app) complicated!
- Youtube
- R Shiny app tutorial # 13 a - how to use renderUI() and uiOutput() in shiny - Dynamic input widgets
- (R Shiny Basic App) #8 Dynamically create Drop Down List source code in github. Code is short. reactive(), observe(), selectInput(), updateSelectInput().
eventReactive()
- 028-actionbutton-demo actionButton() and eventReactive()
- Using Action and Reset Buttons actionButton(), reactiveValues(), observeEvent() and eventReactive()
- https://shiny.rstudio.com/reference/shiny/1.0.3/observeEvent.html
- observeEvent() and eventReactive() from Mastering Shiny
- Shiny: what is the difference between observeEvent and eventReactive?
- eventReactive(eventExpr, handlerExpr, ...) creates a reactive value that changes based on the eventExpr. It seems we do not care much about the returned value. handleExpr is like output$SOMETHING.
- observeEvent(eventExpr, valueExpr, ...) simply is triggered based on eventExpr. It returns a reactive expression object.
Files
shinyFiles
shinyFiles package. This package extends the functionality of shiny by providing an API for client side access to the server file system. As many shiny apps are run locally this is equivalent to accessing the filesystem of the users own computer, without the overhead of copying files to temporary locations that is tied to the use of fileInput().
Password protection
- http://ipub.com/shiny-password-protect/
- https://auth0.com/blog/adding-authentication-to-shiny-server/
- https://www.r-bloggers.com/password-protect-shiny-apps/
- Authentication of Shiny-server Application Using a Simple Method
- Polished is an R package that adds authentication and user administration to your Shiny apps.
Install all required R packages
http://padamson.github.io/r/shiny/2016/03/13/install-required-r-packages.html
Icons
R Shiny & FontAwesome Icons – How to Use Them in Your Dashboards
Building a Shiny App as a Package
- https://rtask.thinkr.fr/blog/building-a-shiny-app-as-a-package/
- Framework for Shiny Apps in R Packages
Three R Shiny tricks to make your Shiny app shines (2/3): Semi-collapsible sidebar
Color picker
https://github.com/daattali/colourpicker
Simulations
Tables
- Announcing the 2020 RStudio Table Contest
- Edit datatables in R shiny app. It uses DT package.
- reactable
Multimedia
Math formula
shinyMatrix
- https://cran.r-project.org/web/packages/shinyMatrix/index.html shinyMatrix: Shiny Matrix Input Field]
- How to Use shinyMatrix and plotly Graphs as Inputs in a Shiny App
Tree
D3
- collapsible d3js trees
- d3po: R package for easy interactive D3 visualization with Shiny
Time series
CSS
Debug
- reactlog: Visually debug your reactivity issues
- Debugging Shiny applications
Talks
Shiny in production: Principles, practices, and tools - Joe Cheng 2019
Tips
Shiny tips & tricks for improving your apps and solving common problems by Dean Attali.
Recreating a Shiny App with Flask
Recreating a Shiny App with Flask
Modularize your shiny apps
- https://shiny.rstudio.com/articles/modules.html
- https://www.r-exercises.com/2018/10/15/modularize-your-shiny-apps-exercises/
- How to Safely Remove a Dynamic Shiny Module
A Shiny-app Serves as Shiny-server Load Balancer
ggtips: adding tooltips boxes to ggplots
Adds interactive tooltip boxes to ggplots (standalone or rendered in Shiny)
Shinyloadtest tools for load testing Shiny applications
shinytest
Shiny-server System Performance Monitoring for Open Source Edition
Build a static website with R Shiny
Build a static website with R Shiny
Embed a shiny app on your website
- https://support.rstudio.com/hc/en-us/articles/217592607-Can-I-embed-shiny-apps-in-other-websites-e-g-iFrames-
- How to embed a Shiny App on Website
- See this example Interactive visualization of survival curves with Shiny where it use iframe to embed a shiny app hosted on shinyapps.io.
<iframe width="750" height="650" scrolling="no" frameborder="no" src="https://hinkelman.shinyapps.io/shiny-survival-covariate/"> </iframe>
Machine learning examples
How To Share Your Machine Learning Models With Shiny
Real Shiny Examples
- CellMinerDB from NCI/NIH.
- UCSCXenaShiny
- voomDDA: Discovery of Diagnostic Biomarkers and Classification of RNA-Seq Data. https://peerj.com/articles/3890/
- Interactive analysis of metagenomics data
- ExpressionDB, An open source platform for distributing genome-scale datasets
- GREIN : GEO RNA-seq Experiments Interactive Navigator and the paper
- SurvELM: An R package for high dimensional survival analysis with extreme learning machine , paper
- Essential guidelines for computational method benchmarking paper
- BISR-RNAseq – an efficient and scalable RNAseq analysis workflow with interactive report generation
- NASQAR: a web-based platform for high-throughput sequencing data analysis and visualization. 2020
- MutationExplorer (sloww) and Source
- ideal: an R/Bioconductor package for interactive differential expression analysis
- BingleSeq- A user-friendly R package for Bulk and Single-cell RNA-Seq data analyses.
- OmicsVolcano: software for intuitive visualization and interactive exploration of high-throughput biological data
- SC1: scRNA-Seq Analysis Pipeline, manuscript
- Azimuth A Shiny web app for mapping datasets using Seurat v4
- cnvscope.nci.nih.gov
- R Shiny in Life Sciences – Top 7 Dashboard Examples
- R Shiny in Government – Top 7 Dashboards You Should See
- classifieR a flexible interactive cloud-application for functional annotation of cancer transcriptomes
- BatchQC package. Batch Effects Quality Control Software. That's why the vignettes do not show any text/plots output. However, an HTML report and other files are created automatically in the working directory.
Interesting Examples
- Convert a data frame to a mediawiki table
- Very shiny holidays! Shiny + JQuery + CSS.
- Shinyfit: Advanced regression modelling in a shiny app
- Probability Calculator App
- Visually explore Probability Distributions with vistributions
- https://github.com/hadley/cran-downloads
install.packages("cranlogs") install.packages("shiny") runGitHub("hadley", "cran-downloads") # cannot open URL 'https://github.com/cran-downloads/hadley/archive/master.tar.gz': # HTTP status was '404 Not Found' system("cd ~/github/; git clone https://github.com/hadley/cran-downloads.git") runApp("~/github/cran-downloads/")
- Exploring Nginx workers load arbitration
- COVID-19
- sars2pack
- Coronavirus COVID-19 statistics and forecast
- https://github.com/nytimes/covid-19-data
- tidycovid19, Covid-19: Explore Your Visualizer Degrees of Freedom
- COVID-19 Tracker: Days since N
- Projections (not shiny)
- https://twitter.com/rafalab/status/1249704266480181250?s=20 (not shiny)
- IMHE COVID-19 CurveFit program, "severe error" in the formulation of the IHME model (not shiny)
- How to create a simple Coronavirus dashboard specific to your country in R
- Whats Cooking ??
- countdown, source
- Hangman from 2nd Annual Shiny Contest.
- A shiny app for exploratory data analysis
Scaling
Long run with Shiny
- Long Running Tasks With Shiny: Challenges and Solutions
- Progress indicators
- How to display a busy indicator in a shiny app?
- shinycssloaders package. Add a loading animation ("spinner") to outputs. Easy to use.
Track Shiny App User Activity With the RStudio Connect Server =
Track Shiny App User Activity With the RStudio Connect Server API
Standalone application
Photon: Building an Electron-Shiny app using a simple RStudio addin