Hi,
I'm trying to build my first Shiny app, then don't desperate if my questions are stupid .
I have a big dataframe with information about companies, their sector and their price historical.
I want to draw a price plot historical for the company choose by the user
My first Idea was to create a selectinput control with inputID ="SI_Stock" fed with all the possible companies and use the renderplot function to draw my plot. It's work fine but due to the number of companies the selectinput is not able to have them all.
Then I decide to create another selectInput with inputID = "SI_Sector" to filter the company list in "SI_Stock" on the sector select by user.
When I select a sector :
1 - The company list in "SI_Stock" is limited to stock in the corresponding sector
2 - My selectInput "SI_Stock" select automatically the first element of the list
3 - The plot is draw
When I select a company :
1 - The app draw the plot for the selected company
2 - Automatically the app select the first element of "SI_Stock" and then cancel the user selection
I understand that the second event reactive function observes and thus cancels the selection..How I can deal with that ?
I would like selectInput "SI_Stocks" to be updated only when there is an event on selectInput "SI_Sector" not for other reasons...
My Code (Sorry I do not see how to give a reproducible code because the dataframe is very big) :
library(shiny)
library(ggplot2)
library(stringr)
library(dplyr)
library(tidyr)
library(reshape2)
# Creation du dataframe
dtf # Dataframe with date, companies name, sector and price historical
names(dtf) <- c("Date", "Names", "Sector","Price")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Price Historical"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput(inputId = "SI_Sector",
label = "Sector:",
choices = sort(unique(dtf$Sector)),
selected = sort(unique(dtf$Sector))[1]),
selectInput(inputId = "SI_Stock",
label = "Stock:",
choices ="",
selected =""),
#choices = sort(unique((dtf %>%
# filter(dtf$Sector==input$Sector))$Names)),
#selected = sort(unique((dtf %>%
#filter(dtf$Sector==input$Sector))$Names))[1]),
sliderInput("slider2", label = h3("Date Range"), min = min(dtf$Date),
max = max(dtf$Date), value = c(min(dtf$Date), max(dtf$Date)))
),
# Show a plot
mainPanel(
plotOutput("Plot")
)
)
)
server <- function(input, output, session) {
observe({
c_Sector <- input$SI_Sector
c_Stock <- input$SI_Stock
updateSelectInput(session, "SI_Stock",
choice =sort(unique((dtf %>%
filter(dtf$Sector==c_Sector))$Names)))
output$Plot <- renderPlot({
dtf %>%
filter(dtf$Names==c_Stock) %>%
gather(key,value, price) %>%
ggplot(aes(x=Date, y=value, colour=key)) +
geom_line()
})
})
}
# Run the application
shinyApp(ui = ui, server = server)
Thanks for your help
Take care