How to create a stand-alone Shiny app for Windows and Mac

In this post I will explain how to create a stand-alone Shiny app for both Windows and Mac platforms. Stand-alone in this case means that the Shiny app will include a portable version of R. Users will not have to install R themselves before running the app.

https://chatgpt.com/c/67adb1fc-b690-800b-aabd-4611c059d2ad

First you need a portable version of R. I explain elsewhere how to build it for Windows and Mac platforms.

Once you have the portable version of R, let’s say in a directory “R-Portable” you should create the following project directory structure:

  • MyShinyApp
    • R-Portable/
    • data/
    • R/
    • app.R
    • dependencies.R
    • run_app.R
    • app.bat
    • app.sh

The file app.R contains all your Shiny code. An example is shown below:

library(shiny)
source("ui.R", local = TRUE)
source("server.R", local = TRUE)
shinyApp(ui, server)

The file dependencies.R installs any R packages you need for your app. It has the following example content:

.libPaths(file.path(getwd(), "R-Portable/library"))

packages <- c("shiny", "ggplot2", "dplyr")  # Add your required packages
install_if_missing <- function(p) {
  if (!requireNamespace(p, quietly = TRUE)) install.packages(p, repos = "https://cloud.r-project.org/")
}

invisible(sapply(packages, install_if_missing))

The file run_app.R has the following content:

source("dependencies.R")
shiny::runApp("app.R", launch.browser = TRUE)

The file app.bat file is a Windows script to start your Shiny app and has the following content:

@echo off
set R_HOME=%~dp0R-Portable
"%R_HOME%\bin\Rscript.exe" run_app.R

The app.sh file is Unix script to start your Shiny app and has the following content:

#!/bin/bash

# Get the absolute path to the script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
R_HOME="$SCRIPT_DIR/R-Portable"

# Check if the portable R installation exists
if [ -x "$R_HOME/bin/Rscript" ]; then
    # Use the portable R version to run the app
    "$R_HOME/bin/Rscript" run_app.R
else
    echo "Portable R not found in $R_HOME"
    echo "Please ensure that the R-Portable directory exists and contains a working R installation."
    exit 1
fi

Scroll to Top