Skip the tutorial and deploy the example now
Deploy a Shiny Application with R to Connect Cloud
This tutorial builds a Shiny application using R and deploys it to Posit Connect Cloud. The project is a simplified version of code available on GitHub.
1. Create a new GitHub repository
Sign in to GitHub and create a new, public repository.
2. Start a new RStudio project
In RStudio:
- Click New Project from the File menu
- Select Version Control
- Select Git
- Paste the URL to your repository in the Repository URL field
- Enter a Desired Project directory name
- Confirm or change the subdirectory location
Now that your project is synced with your GitHub repository, you are ready to begin coding.
From the New File dropdown or the New File option from the File menu:
- Select R Script
- Save the blank file as
app.R
3. Build the application
Copy and paste the code below into app.R
.
# Load packages used by the app. Install missing packages, if needed.
library(shiny)
library(bslib)
library(thematic)
library(tidyverse)
library(gitlink)
# Read data from a CSV file and perform data preprocessing
<- read_csv("data/expansions.csv") |>
expansions = factor(evaluation, levels = c("None", "A", "B")),
mutate(evaluation = factor(propensity, levels = c("Good", "Average", "Poor")))
propensity
# Compute expansion rates by trial and group
<- expansions |>
expansion_groups |>
group_by(industry, propensity, contract, evaluation) = round(mean(outcome == "Won")* 100),
summarize(success_rate = round(mean(amount)),
avg_amount = round(mean(days)),
avg_days = n()) |>
n
ungroup()
# Compute expansion rates by trial
<- expansions |>
overall_rates |>
group_by(evaluation) = round(mean(outcome == "Won"), 2))
summarise(rate
# Restructure expansion rates by trial as a vector
<- structure(overall_rates$rate, names = overall_rates$evaluation)
rates
# Define lists for propensity, contract and industry choices
<- c("Good", "Average", "Poor")
propensities <- c("Monthly", "Annual")
contracts <- c("Academia",
industries "Energy",
"Finance",
"Government",
"Healthcare",
"Insurance",
"Manufacturing",
"Non-Profit",
"Pharmaceuticals",
"Technology")
# Set the default theme for ggplot2 plots
ggplot2::theme_set(ggplot2::theme_minimal())
# Apply the CSS used by the Shiny app to the ggplot2 plots
thematic_shiny()
# Define the Shiny UI layout
<- page_sidebar(
ui
# Set CSS theme
= bs_theme(bootswatch = "darkly",
theme = "#222222",
bg = "#86C7ED",
fg ="#86C7ED"),
success
# Add title
= "Effectiveness of DemoCo App Free Trial by Customer Segment",
title
# Add sidebar elements
= sidebar(title = "Select a segment of data to view",
sidebar class ="bg-secondary",
"industry", "Select industries", choices = industries, selected = "", multiple = TRUE),
selectInput("propensity", "Select propensities to buy", choices = propensities, selected = "", multiple = TRUE),
selectInput("contract", "Select contract types", choices = contracts, selected = "", multiple = TRUE),
selectInput("This app compares the effectiveness of two types of free trials, A (30-days) and B (100-days), at converting users into customers.",
= "logo.png", width = "100%", height = "auto")),
tags$img(src
# Layout non-sidebar elements
"Conversions over time"),
layout_columns(card(card_header("line")),
plotOutput("Conversion rates"),
card(card_header("bar")),
plotOutput(= "Recommended Trial",
value_box(title = textOutput("recommended_eval"),
value = "secondary"),
theme_color = "Customers",
value_box(title = textOutput("number_of_customers"),
value = "secondary"),
theme_color = "Avg Spend",
value_box(title = textOutput("average_spend"),
value = "secondary"),
theme_color "Conversion rates by subgroup"),
card(card_header("table")),
tableOutput(= c(8, 4, 4, 4, 4, 12),
col_widths = c(4, 1.5, 3))
row_heights
)
# Define the Shiny server function
<- function(input, output) {
server
# Provide default values for industry, propensity, and contract selections
<- reactive({
selected_industries if (is.null(input$industry)) industries else input$industry
})
<- reactive({
selected_propensities if (is.null(input$propensity)) propensities else input$propensity
})
<- reactive({
selected_contracts if (is.null(input$contract)) contracts else input$contract
})
# Filter data against selections
<- reactive({
filtered_expansions |>
expansions filter(industry %in% selected_industries(),
%in% selected_propensities(),
propensity %in% selected_contracts())
contract
})
# Compute conversions by month
<- reactive({
conversions |>
filtered_expansions() = floor_date(date, unit = "month")) |>
mutate(date |>
group_by(date, evaluation) = sum(outcome == "Won")) |>
summarize(n
ungroup()
})
# Retrieve conversion rates for selected groups
<- reactive({
groups |>
expansion_groups filter(industry %in% selected_industries(),
%in% selected_propensities(),
propensity %in% selected_contracts())
contract
})
# Render text for recommended trial
<- renderText({
output$recommended_eval <-
recommendation |>
filtered_expansions() |>
group_by(evaluation) = mean(outcome == "Won")) |>
summarise(rate filter(rate == max(rate)) |>
pull(evaluation)
as.character(recommendation[1])
})
# Render text for number of customers
<- renderText({
output$number_of_customers sum(filtered_expansions()$outcome == "Won") |>
format(big.mark = ",")
})
# Render text for average spend
<- renderText({
output$average_spend <-
x |>
filtered_expansions() filter(outcome == "Won") |>
= round(mean(amount))) |>
summarise(spend
pull(spend)
"${x}")
str_glue(
})
# Render line plot for conversions over time
<- renderPlot({
output$line = date, y = n, color = evaluation)) +
ggplot(conversions(), aes(x +
geom_line() = element_blank()) +
theme(axis.title = "Trial Type")
labs(color
})
# Render bar plot for conversion rates by subgroup
<- renderPlot({
output$bar |>
groups() |>
group_by(evaluation) = round(sum(n * success_rate) / sum(n), 2)) |>
summarise(rate = evaluation, y = rate, fill = evaluation)) +
ggplot(aes(x +
geom_col() = "none") +
guides(fill = element_blank()) +
theme(axis.title = c(0, 100))
scale_y_continuous(limits
})
# Render table for conversion rates by subgroup
<- renderTable({
output$table |>
groups() |>
select(industry, propensity, contract, evaluation, success_rate) = evaluation, values_from = success_rate)
pivot_wider(names_from
},= 0)
digits
}
# Create the Shiny app
= ui, server = server) shinyApp(ui
Add the data file
This application uses a data file named expansions.csv
that is available here.
To add it to your project:
- Create a new folder named
data
- Create a new Text File named
expansions.csv
within thedata
folder - Copy and paste the data from the link above into your
expansions.csv
file
Preview the application
In RStudio when looking at app.R
, click the Run button. This previews your application locally.
Add dependency file
The last thing you need to do is create a dependency file that will provide Connect Cloud with enough information to rebuild your content during deployment. Although there are multiple approaches to achieve this, Connect Cloud exclusively uses a manifest.json file.
To create this file, load the rsconnect
library and run the writeManifest()
function.
rsconnect::writeManifest()
This function creates a .json file named manifest.json
that will tell Connect Cloud (1) what version of R to use and (2) what packages and versions are required.
3. Push to GitHub
Now that everything looks good and we’ve created a file to help reproduce your local environment, it is time to get the code on GitHub.
- Navigate to the Git tab in your RStudio project
- Click Commit
- Select the checkbox to stage each new or revised file
- Enter a commit message
- Click Commit
- Click the Push icon
Your repository now has everything it needs for Connect Cloud.
4. Deploy to Posit Connect Cloud
Follow the steps below to deploy your project to Connect Cloud.
Sign in to Connect Cloud.
Click the Publish icon button on the top of your Profile page
Select Shiny
Select the public repository that you created in this tutorial
Confirm the branch
Select app.R as the primary file
Click Publish
Publishing will display status updates during the deployment process. You will also find build logs streaming on the lower part of the screen.
Congratulations! You successfully deployed to Connect Cloud and are now able to share the link with others.
5. Republish the application
If you update the code to your application or the underlying data source, commit and push the changes to your GitHub repository.
Once the repository has the updated code, you can republish the application on Connect Cloud by going to your Content List and clicking the republish icon.