How can I get the list of choices in a SelectInpute?
ui.R
selectInput(inputId = "select_gender",
label = "Gender",
choices = c("Male","Female"),
width = 150
)
server.R
# Something like...
genders <- input$select_gender["choices"]
# So that the gender would be:
> genders
[1] Male Female
From the scoping rules of Shiny:
Objects defined in global.R are similar to those defined in app.R outside of the server function definition, with one important difference: they are also visible to the code in the ui object. This is because they are loaded into the global environment of the R session; all R code in a Shiny app is run in the global environment or a child of it.
However, this doesn't mean that objects defined in the app.R can't be used on both the UI and Server side, they just belong to a different environment.
For example:
library("shiny")
library("pryr")
# or in global.R
genders <- c("Male", "Female")
gen_env <- where("genders")
par_env <- parent.env(gen_env)
ui <- fluidPage(
selectInput("shiny_gender", "Select Gender", choices = genders),
verbatimTextOutput("selected_gender_index"),
p("The `genders` object belongs to the environment:"),
verbatimTextOutput("gen_env_print"),
p("Which is the child of the environment:"),
verbatimTextOutput("par_env_print")
)
server <- function(input, output) {
output$selected_gender_index <- renderPrint({
# use the 'genders' vector on the server side as well
which(genders %in% input$shiny_gender)
})
output$gen_env_print <- renderPrint(gen_env)
output$par_env_print <- renderPrint(par_env)
}
shinyApp(ui = ui, server = server)
I've looked for get choices of selectinput but without recompute the choices. For example if the datas come from database, or file or other source.
And I didn't get answer. (I get this question but not the solution for me).
Here is ma solution which also could set the selectinput from the server:
set the choices list in a reactive function
build the selectinput in the server side (with the choices list reactive function)
set and get the selectinput in the server side
Here is the code
options(encoding = "UTF-8")
library("shiny")
library("pryr")
ui <- fluidPage(
uiOutput("shiny_gender.UI"),
verbatimTextOutput("selected_gender_index"),
p("The `genders` object belongs to the environment:"),
verbatimTextOutput("gen_env_print"),
p("Which is the child of the environment:"),
verbatimTextOutput("par_env_print"),
p(""),
textInput("set_input_txt","Set the car in letter (for example `Datsun 710`)",
#" Set the Select Input Male / Female ",
""),
actionButton("submit","submit")
)
server <- function(input, output, session) {
observeEvent(
c(input$submit),
{
if (input$submit>0) {
updateSelectInput(session, "shiny_gender",
# server = TRUE, if updateSelectizeInput
choices =shiny_gender.list(),
selected = input$set_input_txt
)
}
}
)
shiny_gender.list <- reactive ({
#c("Male", "Female")
rownames(mtcars)
})
output$shiny_gender.UI <- renderUI({
selectInput( "shiny_gender",
label="Select car",#"Select Gender",
choices =shiny_gender.list()
)
})
output$selected_gender_index <- renderPrint({
which(shiny_gender.list() %in% input$shiny_gender)
})
output$gen_env_print <- renderPrint(where("shiny_gender.list"))
output$par_env_print <- renderPrint(parent.env( where("shiny_gender.list")))
}
shinyApp(ui = ui, server = server)
Related
I want to hide a selectInput so it doesnt let people try and use it before the data has loaded.
Snippet of UI code.
ui <- dashboardPage(
dashboardHeader(title = "TCS Adverse Event Search Tool"),
dashboardSidebar(
sidebarMenu(
shinycssloaders::withSpinner(
selectInput("ingredients",
label = "Select one or more Active Ingredients:",
choices = NULL,
multi=TRUE)
),
In my server function I have this:
server <- function(input, output, session) {
# get main data frame
ingredients_df <- reactive({
ingredients_df <- read.csv(file="/projects/other/pv_compliance/active_ingredients.csv")
print(paste(nrow(ingredients_df)," active ingredient rows returned"))
return(ingredients_df)
})
cases_df <- reactive({
cases_df <- read.csv(file="/projects/other/pv_compliance/adverse_events.csv")
print(paste(nrow(cases_df)," case rows returned"))
return(cases_df)
})
observeEvent(ingredients_df(), {
updateSelectInput(session,
"ingredients",
choices = ingredients_df()$PRIMARY_SUSPECT_KEY_INGREDIENT,
selected = NULL
)
})
Two things are happening...
the set of widgets now appear about halfway down the sidebar and not the top
the css loader does not display when the updateSelectInput is getting the data
I saw some previous questions that may circle around this issue, but I couldn't find a clear answer to that.
My problem is that an ui element added using insertUI that depends on a reactive value does not update.
In the example I gave below, if one adds the new selectInput using the button and then changes the gender selection, the choices are updated only in the first selectInput.
The question is: is there an "official" way to make this selectInput reactive? I can imagine some workarounds, but they are not ideal.
server.R
library(shiny)
library(tidyverse)
server <- function(input, output, session) {
data <- reactive({
req(input$genderSelection)
starwars %>%
filter(gender == input$genderSelection)
})
output$characterSelection1 <- renderUI({
selectInput(
"char1",
"Character 1",
choices = data() %>%
.$name
)
})
observeEvent(
input$btn,
{
insertUI(
selector = "#selection2",
where = "beforeEnd",
ui = selectInput(
"char2",
"Character 2",
choices = data() %>%
.$name
)
)
}
)
}
ui.R
ui <- fluidPage(
radioButtons(
"genderSelection",
"Gender",
choices = c("male", "female")
),
uiOutput("characterSelection1"),
tags$div(
id = "selection2",
actionButton("btn", "Add selection")
)
)
I created a simple plot that when the user clicks on a point it generates another plot on a second tab, Page_2 -- is it possible to add some custom JS so that when the user clicks on the point they are automatically re-routed to the Page_2 tab?
library(shiny)
library(plotly)
library(tidyverse)
# ui with two panes
# when you click on the outlier in the first plot
# you are routed to the second "point explorer" page
ui <- navbarPage("Plotly On Click Switch Pane",
tabPanel("Page_1",
mainPanel(plotlyOutput("plot"),
tableOutput("text"))),
tabPanel("Page_2",
mainPanel(plotlyOutput("ind_plot"))
))
server <- function(input, output) {
# plot on first page
output$plot <- renderPlotly({
ggplotly(source = "sub_iris",
ggplot(iris, aes(x = Species, y = Petal.Width)) +
geom_boxplot()
)
})
# create reactive for subset plot on second tab
s <- reactive({ event_data("plotly_click", source = "sub_iris") })
# plot text on first page (test)
output$text <- renderTable(event_data("plotly_click", source = "sub_iris"))
# this is the correct plot, but I want to re-route the user here when they click on a point
output$ind_plot <- renderPlotly({
iris_ind <- subset(iris)[subset(s(), curveNumber == 0)$pointNumber + 1,]
ggplotly(
ggplot(iris_ind, aes(x = Species, y = Sepal.Length)) +
geom_bar(stat = "identity")
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
You can use updateNavbarPage after providing your navbarPage with an id:
library(shiny)
library(plotly)
library(tidyverse)
# ui with two panes
# when you click on the outlier in the first plot
# you are routed to the second "point explorer" page
ui <- navbarPage("Plotly On Click Switch Pane", id = "navbarID",
tabPanel("Page_1",
mainPanel(plotlyOutput("plot"),
tableOutput("text"))),
tabPanel("Page_2",
mainPanel(plotlyOutput("ind_plot"))
))
server <- function(input, output, session) {
# plot on first page
output$plot <- renderPlotly({
ggplotly(source = "sub_iris",
ggplot(iris, aes(x = Species, y = Petal.Width)) +
geom_boxplot()
)
})
# create reactive for subset plot on second tab
s <- reactive({
event_data("plotly_click", source = "sub_iris")
})
observeEvent(s(), {
updateNavbarPage(session, inputId = "navbarID", selected = "Page_2")
})
# plot text on first page (test)
output$text <- renderTable(req(s()))
# this is the correct plot, but I want to re-route the user here when they click on a point
output$ind_plot <- renderPlotly({
req(s())
iris_ind <- subset(iris)[subset(s(), curveNumber == 0)$pointNumber + 1,]
ggplotly(
ggplot(iris_ind, aes(x = Species, y = Sepal.Length)) +
geom_bar(stat = "identity")
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
I am trying filter my data using the dplyr package inside the reactive function in Shiny, but nothing is being displayed in the output. The data is supposed to be filtered by levels of the variable "Country".
Here is the code I have used and the dataframe
datos<-data.frame(time=c(rep(c(2001, 2002),3)), values=c(100,200,300,600,700,800), country=c(rep("Uruguay",2),rep("France",2),rep("United States",2)))
ui <- fluidPage(
selectInput(inputId ="pais", label="Choose a country",
choices =levels(datos$country), selected = "Uruguay"),
plotOutput(outputId ="barplot")
)
server <- function(input, output) {
datos3 <- reactive({
datos%>%
filter(country=="input$pais")
})
output$barplot<-renderPlot({
ggplot(datos3(),aes(x=time,y=values))+geom_bar(stat="Identity")
})
}
shinyApp(ui = ui, server = server)
I am supposed to obtain the values for the selected country, by time period.
You didn't need the quotation marks on "input$pais".
Here is the code with that and the extra + in the ggplot section removed.
library(shiny)
library(tidyverse)
datos<-data.frame(time=c(rep(c(2001, 2002),3)), values=c(100,200,300,600,700,800), country=c(rep("Uruguay",2),rep("France",2),rep("United States",2)))
ui <- fluidPage(
selectInput(inputId ="pais", label="Choose a country",
choices =levels(datos$country), selected = "Uruguay"),
plotOutput(outputId ="barplot")
)
server <- function(input, output) {
datos3 <- reactive({
datos%>%
filter(country==input$pais) #this bit has been changed
})
output$barplot<-renderPlot({
ggplot(datos3(),aes(x=time,y=values))+geom_bar(stat="Identity")
})
}
shinyApp(ui = ui, server = server)
I'm trying to use shiny to create a bar graph for a state that is selected via drop-down box. I'm quite new to R and I've tried a variety of examples to no avail. I have three variables (state, claim #, total $) and for each state there are five values. So something like this:
state <- c("PA", "TX", "NY")
claim_num <- c(1:15)
total <- sample(1000:5000, 15)
df <- (state, claim_num, total)
I want to have something similar to https://beta.rstudioconnect.com/jjallaire/shiny-embedding/#inline-app but I don't know if I can format my data in that was since I would have a lot of NAs.
Do you mean something like this (you can download and run the example)?
library(shiny)
ui <- shinyUI(
fluidPage(
titlePanel("Sample Shiny App"),
sidebarLayout(
sidebarPanel(
uiOutput("stateInput")
),
mainPanel(
plotOutput("statePlot")
)
)
))
server <- shinyServer(function(input, output) {
state <- sample(state.abb, 3, replace = FALSE)
total <- sample(1000:5000, 15)
claimNumber <- 1:15
data <- data.frame(state, total, claimNumber)
output$stateInput <- renderUI({
selectInput(
inputId = "state",
label = "Select a State:",
choices = levels(data$state)
)
})
output$statePlot <- renderPlot({
hist(data$total[data$state == input$state])
})
})
shinyApp(ui = ui, server = server)
What we're doing is taking the list of unique states available in our data frame and passing those to our selectInput that renders as a dropdown in the UI. From here, we can access whatever value the user has selected through the input$state object. More generally, we can access inputs based on whatever we define the inputId to be (in this particular case, we call it state).
Having grabbed the user input, we can then subset the data frame to only return values that correspond to the user-defined state and, in this case, pass those totals values to a plot that we render as output.