Dataset: https://www.kaggle.com/mirichoi0218/insurance
Hi, I have a problem with shiny library. Wanted to create app that will show the Charges depending on the age, region and children. Unfortunately, the histogram doesn't work.
ui <- fluidPage(
titlePanel("Insurance charges"),
sidebarLayout(
sidebarPanel(
sliderInput("ageInput", "Age", 18, 64, 41),
radioButtons("childrenInput", "Liczba dzieci",
choices = c("0", "1", "2", "3",'4','5'),
selected = "0"),
selectInput("regionInput", "Region",
choices = c("NE", "NW", "SE","SW"))
),
mainPanel(
plotOutput("coolplot"),
br(), br(),
tableOutput("results")
)
)
)
server <- function(input, output) {
output$coolplot <- renderPlot({
filtered <-
insurance %>%
filter(age >= input$ageInput[1],
age <= input$ageInput[2],
children == input$childrenInput,
region == input$regionInput
)
ggplot(filtered, aes(insurance$charges))
geom_histogram()
})
}
shinyApp(ui = ui, server = server)
CodePudding user response:
The major issue with your code is that
you map
insurance$chargesonxinggplot(). That's why you always get a histogram for the total dataset. Simply useaes(charges)to use the column from yourfiltereddataset.Not sure about that. Maybe your recoded your data, but the regions in the Kaggle dataset have labels "northeast", "northwest", .... To account for that you could use a named vector for the
choicesin theselectInputFinally, you have to use a vector of length 2 for the
valueof thesliderInputto get a range slider.
And as an example on how to provide a minimal reproducible example I used a random fake dataset for the reprex.
library(shiny)
library(ggplot2)
library(dplyr)
ui <- fluidPage(
titlePanel("Insurance charges"),
sidebarLayout(
sidebarPanel(
sliderInput("ageInput", "Age", min = 18, max = 64, value = c(18, 41)),
radioButtons("childrenInput", "Liczba dzieci",
choices = c("0", "1", "2", "3", "4", "5"),
selected = "0"
),
selectInput("regionInput", "Region",
choices = c("NE" = "northeast", "NW" = "northwest", "SE" = "southeast", "SW" = "southwest")
)
),
mainPanel(
plotOutput("coolplot"),
br(), br(),
tableOutput("results")
)
)
)
server <- function(input, output) {
output$coolplot <- renderPlot({
filtered <- insurance %>%
filter(
age >= input$ageInput[1],
age <= input$ageInput[2],
children == input$childrenInput,
region == input$regionInput
)
ggplot(filtered, aes(charges))
geom_histogram()
})
}
shinyApp(ui = ui, server = server)

DATA
set.seed(123)
insurance <- data.frame(
age = sample(18:64, 1000, replace = TRUE),
children = sample(0:5, 1000, replace = TRUE),
region = sample(c("southwest", "southeast", "northwest", "northeast"), 1000, replace = TRUE),
charges = runif(1000, 3000, 40000)
)
