Returning value from a shiny app in an interactive R session

Viewed 345

I am making a little interactive widget using shiny. The purpose of the widget is not to create a stand-alone shiny web app. Instead, the idea is to run the widget in an interactive R session, to allow the user to interactively manipulate data from the session using a GUI. The output of the Shiny app should then be returned to the user session by the function.

The 'true' purpose of my widget is to interactively select data points on a plot, and return the values selected as the output of the function. However, to make a nice and simple REPREX, I have chosen a simpler scenario:

multiply_me <-
  function(number1) {
    require(shiny)
    
    shinyApp(
      ui = fluidPage(
        selectInput('number2', label = 'Enter multiplication factor', choices = c(1, 2, 3)),
        textOutput('result')
        ),
      
      server = function(input, output) {
        output$result = renderText(number1 * as.numeric(input$number2))
      }
    )
    
  }

In the multiply_me function, the user can take a variable from the existing interactive session (number1), and run multiply_me(number1) to initiate the shiny widget. The widget then allows the user to select multiplication factors on the slider and view the result.

But how do I return the result of the calculation (number1 * number 2) to the interactive R session?

2 Answers

You could use stopApp:

multiply_me <-
  function(number1) {
    require(shiny)
    
    runApp(list(
      ui = fluidPage(
        selectInput('number2', label = 'Enter multiplication factor', choices = c(1, 2, 3)),
        textOutput('result'),
        actionButton('ok','OK')
      ),
      
      server = function(input, output) {
        output$result = renderText(number1 * as.numeric(input$number2))
        observe({
          if(input$ok){
            stopApp(number1 * as.numeric(input$number2))}
         })
       }
    ))
  }

multiply_me(1)
[1] 2

You can also use stopApp in a Shiny gadget:

library(shiny)
library(miniUI)

multiply_me <- function(number1) {
  
  ui <- miniPage(
    gadgetTitleBar("My Gadget"),
    miniContentPanel(
      selectInput(
        'number2', label = 'Enter multiplication factor', choices = c(1, 2, 3)
      ),
      textOutput('result')
    )
  )
  
  server <- function(input, output, session) {
    
    result <- reactive({
      number1 * as.numeric(input$number2)
    })

    output$result <- renderText(result())
    
    observeEvent(input$done, {
      returnValue <- result()
      stopApp(returnValue)
    })
    
    observeEvent(input$cancel, {
      stopApp()
    })
    
  }
  
  runGadget(ui, server)
}

The gadget opens in the RStudio viewer, and it has two buttons 'done' and 'cancel', so that you don't need to implement these buttons.

Related