Hi all!
I am super new to R and computer science in general and tried to write my first shiny app using the Titanic dataset. I would like to let the user choose which class and which sex should be displayed on a histogram. The ui was rather simple but I am struggling with the server function. I would be really grateful if somebody could help me and explain how to include the if statements. I will include my code here:
library(shiny)
library(shinythemes)
library(dplyr)
library(ggplot2)
library(readr)
Titanic <- as.data.frame(Titanic)
ui <- fluidPage(
titlePanel("Survival Titanic"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "Passenger_Class",
label = "Enter passenger category:",
choices = c("1st", "2nd", "3rd", "Crew", "All") ),
selectInput(inputId = "Sex",
label = "Enter gender of interest",
choices = c("Male", "Female", "Both") ),
submitButton(text = "Create Plot")),
mainPanel(plotOutput(outputId = "histogram"))))
server <- function(input, output) {
selectData = reactive({
ifelse (input$PassengerClass =="All", Titanic_subset <- Titanic,
Titanic_subset <- Titanic %>% filter(Class == input$PassengerClass))
if (input$Sex == "Male") {Titanic_subset <- Titanic_subset %>% filter(Sex == "Male")}
if (input$Sex == "Female") {Titanic_subset <- Titanic_subset %>% filter(Sex == "Female")}
if (input$Sex == "Both") {Titanic_subset <- Titanic_subset}
output$histogram <- renderPlot({
ggplot(Titanic, aes( x= Class, y= Freq, fill = Survived) ) +
geom_bar(stat = "identity", position = position_dodge() ) +
ylab ("Number of Passengers")})
})}
Run
shinyApp(ui = ui, server = server)