2

I am relatively new to Shiny and am trying to create an app that creates a global variable that I can then pass to an R script. Here is an example of my Shiny App:

library(shiny)
 
ui <- fluidPage(
  titlePanel("Hello"),
  br(),
  h3("Welcome"),
  
  sidebarLayout(
    
    sidebarPanel(
      h1("Enter parameter value"),
      selectInput("datamodel", "Update Data Model",
                  choices = c("Yes", "No"),
                  selected = "No")
    ),
    
    mainPanel(
      h1("Output")
      
    )
  ))

# Define server logic
server <- function(input, output) {
  
  observe({
    Update_Data_Model <<- input$datamodel
  })  
  
  source("Authentication.R")
  
}


# Run the application shinyApp(ui = ui, server = server) 

The UI is created and I am able to create a global variable called Update_Data_Model to pass to my R script called Authentication.R, however the R script runs before I have time to enter the input variable in the UI.

Is there a way to execute the R script once the input variables have been entered in the UI?

1 Answer 1

1

You can use observeEvent on the input itself, so it will only execute when that input changes:

library(shiny)

ui <- fluidPage(
  titlePanel("Hello"),
  br(),
  h3("Welcome"),

  sidebarLayout(

    sidebarPanel(
      h1("Enter parameter value"),
      selectInput("datamodel", "Update Data Model",
                  choices = c("Yes", "No"),
                  selected = "No")
    ),

    mainPanel(
      h1("Output")

    )
  ))

# Define server logic
server <- function(input, output) {

    observeEvent(input$datamodel, {

        Update_Data_Model <<- input$datamodel

        if(input$datamodel == 'Yes') {

            source("Authentication.R")

        }

    })

}

shinyApp(ui = ui, server = server)

Consider using an action button rather than a dropdown, it could be a bit more intuitive for you and your users:

library(shiny)

ui <- fluidPage(

    actionButton("mybutton", "Update Data Model")

)

server <- function(input, output) {

    observeEvent(input$mybutton, {

        source("Authentication.R")

    })

}

shinyApp(ui = ui, server = server)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. How would I go about using an action button? Could you provide an example like you did above for the use of observe event?
@SteveM I've updated the answer above to include one using an action button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.