Shiny

From 太極
Revision as of 13:02, 18 October 2024 by Brb (talk | contribs) (→‎Shiny Assistant)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.

ShinyHello.png Shinympg.png ShinyReactivity.png ShinyTabsets.png ShinyUpload.png

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

Deploy to run locally

Run Shiny Apps Locally 2021

Follow the instruction here, we can do as following (Tested on Windows OS)

  1. 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
  2. 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.
  3. 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.
  4. Open your browser (Chrome or Firefox works), and type the address http://localhost:7510. You will see something magic happen.
  5. If we don't want to play with it, we can close the browser and close the command console (hit 'x')too.

How to run an R shiny app

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 Github Pages: shinylive

Deploy to Digital Ocean

How to deploy Shiny application to Digital Ocean using GitHub Actions

Deploy on shinyapps.io: rsconnect package

About the account

Shinyapps.io can accept google account to sign up.

Note:

  1. Default System Packages.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Caveats:

  1. I cannot upload my shiny app shinySurvival when it contains data in a subdirectory.
  2. When the app is running perfectly locally, it gives some errors when it is deployed to the shinyapps.io. Looking at the app log does not help too much.

deployApp()

  • Choose which files ignored deploy to shinyapps.io. See Deploy to Shinyapps.io from Github Actions
    deployApp(, appFiles= c("app.R" #, you can specify which files to deploy, 
                                     #or keep this NULL to deploy everything
                             ),
              appName = error_on_missing_name("MASTERNAME"),
              appTitle = "shinyapplication")
    

Packages

  • 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.
  • When you deploy your application, the rsconnect package detects the packages that your application uses by looking for explicit library() calls within your application. Be aware that you should not have an explicit install.packages() call within your ui.R or server.R files.
  • Currently the shinyapps.io service supports deploying packages installed from CRAN, GitHub, and BioConductor.
  • rsconnect::appDependencies() - Recursively detect all package dependencies for an application.
  • Error when trying to deploy to shinyapps.io: Application depends on package "package" but it is not. You have to fool the shinyapps (or rsconnect) package a bit so that it does not detect package as a literal package name.
    do.call(library, list(package = package, character.only = TRUE))
    
  • How to specify package versions when deploying Shiny app to shinyapps.io? See the next item.
  • Shiny app which depends on package on GitHub? You should not install packages inside your shiny app, just install it locally and rsconnect will figure out how to install it based on your local library, you just have to load the library inside your app. Remember packageDescription() records all information even a package installed from a specific commit from Github repository.
  • (Is this outdated?) In order for BioConductor packages to install succesfully on shinyapps.io, the repos option must be configured, either directly or by using setRepositories(), to include the BioConductor repositories in addition to CRAN. setRepositories()
    setRepositories(addURLs = c(BioC = "https://bioconductor.org/packages/3.8/bioc"))
    
  • Deploy shiny app using custom package. Also use renv or packrat package.
  • How to manage R package dependencies for shiny app deployment (docker) packrat
  • Deploying packrat projects to Shiny Server Pro packrat
  • Building Web Apps with R Shiny ebook
  • Deploy to Shinyapps.io from Github Actions

Deploying a development version of a shiny app

rsconnect::deployApp(..., appName="MyApp")
rsconnect::deployApp(..., appName="MyApp_dev")

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

RHEL/CentOS 7

https://www.vultr.com/docs/how-to-install-shiny-server-on-centos-7

Raspberry Pi

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

Google analytics

https://docs.rstudio.com/shiny-server/#google-analytics

Reverse proxy: Deploy your own shiny server

Shiny https: Securing Shiny Open Source with SSL

Securing Shiny Server with Caddy

Shiny for Python

https://shiny.rstudio.com/py/

Shiny Assistant

Simplifying Parts Of A Shiny App by Creating Functions

Simplifying Parts Of A Shiny App by Creating Functions

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

The R Shiny packages you need for your web apps

https://www.r-bloggers.com/2017/07/the-r-shiny-packages-you-need-for-your-web-apps/

Other web apps

Ten simple rules for researchers who want to develop web apps

Shiny + Docker

Dashboard

shinydashboard

flexdashboard

shinyalert: create pretty popup messages (modals) in Shiny

shinyalert

shinyjs

shinyjs

Dash bio for R

Introducing Dash Bio for R

Theme

shinytheme

bslib

R Shiny bslib – How to Work With Bootstrap Themes in Shiny

bootstraplib

How to use bootstraplib's Live Theme Previewer to customize Shiny apps?

shiny + databases

tags, hyperlinks

dates

websocket

CentOS

Gallery

git clone https://github.com/rstudio/shiny-examples.git
shiny::runApp("~/github/shiny-examples/018-datatable-options/")

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)

navbarPage

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

reactive

actionButton and isolate

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

eventReactive()

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

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
  • Image not showing R Shiny (displayed as broken)
    • Put the png file in the www directory
    • Put your R code in the app.R file and run it through runApp() or the Run App icon in RStudio. It does not work if we call it by shinyApp() function.
  • Example
    library(shiny)
    library(survival)
    
    ui <- fluidPage(
       titlePanel(
          title = tags$div(tags$img(src = "icon.png", height = "32px", width = "32px"), 
                           "Interactive Kaplan Meier Plot", 
                           style = "background-color: black; color: white; padding: 10px;")),
       sidebarLayout(
          sidebarPanel(
             radioButtons("survivalType", "Choose survival data type:",
                          choices = list("Overall Survival" = "os", "Progression Free Survival" = "pfs"),
                          selected = "os")
          ),
          mainPanel(
             plotOutput("kmPlot")
          )
       )
    )

How do I add a favicon to my Shiny app

Adding a favicon to your Shiny app can be done by placing the favicon file in the www directory of your Shiny app and then using the tags$link function in your UI to link to it. Here’s how you can do it:

  1. Place your favicon file (e.g., favicon.ico) in the www directory of your Shiny app.
  2. In your UI, add the following line inside the fluidPage or navbarPage function:
    tags$head(tags$link(rel = "shortcut icon", href = "favicon.ico", type = "image/x-icon"))
    
  3. Here’s an example of how it might look in a Shiny app:
    ui <- fluidPage(
       titlePanel("My Shiny App"),
       tags$head(tags$link(rel = "shortcut icon", href = "favicon.ico", type = "image/x-icon")),
       # Rest of your UI code...
    )
    
    server <- function(input, output) {
       # Your server code...
    }
    
    shinyApp(ui = ui, server = server)
    

Websites to convert an image to a favicon:

Building a Shiny App as a Package

Collapsible menu

Three R Shiny tricks to make your Shiny app shines (2/3): Semi-collapsible sidebar

Color picker

https://github.com/daattali/colourpicker

Simulations

Monte Carlo Shiny

Tables

Multimedia

Shiny and Reactive Multimedia

Math formula

shinyMatrix

Tree

shinyTree

D3

Time series

dygraphs

CSS

Debug

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.

Adding a website

Adding a website next to your Shiny server

A Guide to Benchmarking Memory Usage

Maximizing Efficiency: A Guide to Benchmarking Memory Usage in Shiny Apps

Recreating a Shiny App with Flask

Recreating a Shiny App with Flask

Webhook

Flask, a popular web framework.

This example assumes that you have a server running at https://yourserver.com/webhook that is set up to receive POST requests.

from flask import Flask, request
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def respond():
    print(request.json)
    return {'status': 'success'}, 200

if __name__ == '__main__':
    app.run(port=5000, debug=True)

In this example, whenever a POST request is made to https://yourserver.com/webhook, the respond function is triggered. This function prints the JSON payload of the request and returns a success status. The JSON payload is the data sent by the application that triggered the webhook. This could be any data related to the event that occurred in the other application. For instance, if the webhook was triggered by a new user signing up, the JSON payload might contain the new user’s details.

You can use the curl command to send a POST request to your local server. Here’s an example:

curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://localhost:5000/webhook

Modularize your shiny apps

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

New in RStudio 1.2: record and run tests for your Shiny code right inside the IDE with the shinytest package

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

<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

Interesting Examples

Scaling

Long run with Shiny

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

Mobile

shinyMobile