# List of required packages
library(tidyverse)
library(shiny)
library(dplyr)
library(babynames)
Class Activity 19
Question 1
We are utilizing the babynames
dataset to explore and visualize how the popularity of specific names has evolved over time.
(c) Create a line plot to visualize the trend of a selected baby name over the years by using renderPlot
, showing the number of occurrences (n)
of the name across different years (year)
.
<- function(input, output) {
server # Use eventReactive to execute code in response to a specific action (button press)
<- eventReactive(input$goButton, {
nameData req(input$name) # Ensure the name input is not empty
%>%
babynames filter(name == isolate(input$name),
== isolate(input$gender)) # Use isolate to prevent reactivity except on button press
sex
})
$nameTrend <- renderPlot({
output# req(nameData()) # Ensure data is available before plotting
ggplot(nameData(), aes(x = year, y = n)) +
geom_line() +
labs(title = paste("Trend for name", isolate(input$name)), # Use isolate to get name input without triggering reactivity
x = "Year", y = "Number of Babies") +
theme_minimal()
}) }
Remember, without isolate
, any change to the inputs (input$name and input$gender)
would immediately trigger the reactive expressions (nameData
and the plotting logic within renderPlot
) to re-execute. This means the plot would update every time the user types a letter in the name input field or changes the gender, rather than waiting for the user to press the goButton
.
(d) Run the Shiny app by combining the UI and server components using shinyApp.
shinyApp(ui, server, options = list(height = 800))
(e). Deploying a Shiny App to shinyapps.io
Open an account on shinyapps.io and follow the steps to deploy one of the apps to shinyapps.io.
Step 1: Create Your Shiny App
Create a file named app.R in a new folder. This folder will contain all the necessary files for your app.
Step 2: Organize Your App Folder
Ensure your app.R file is saved in a dedicated folder for your app. This folder can also include any additional data files, data folder for data, or other resources your app needs.
Step 3: Deploy Your App to shinyapps.io
Before deploying, you’ll need to set up an account on shinyapps.io
. Use the rsconnect package to authenticate your R session with your shinyapps.io
account. You will need the API key from your shinyapps.io
account dashboard.
library(rsconnect)
::setAccountInfo(name='<account-name>',
rsconnecttoken='<api-token>',
secret='<api-secret>')
Replace <account-name>
, <api-token>
, and <api-secret>
with your actual account name and API key details. Navigate to your app folder in RStudio, or set the working directory to your app folder in R:
setwd("/path/to/your/app")
Deploy your app using the deployApp
function:
::deployApp() rsconnect
Follow the prompts in the R console. Once the deployment process completes, you will receive a URL to access your app hosted on shinyapps.io
.