remi
remi

Reputation: 779

Shiny reactive expression call to local function

Using Shiny to build an app, I'm having an issue with a reactive call to a locally defined function. An emulating example:

  <server.R>
  shinyServer(function(input, output) { 
  myfunc <- function(x) x+1
  myreac <- reactive({
          y <- myfunc(input$var)
          y
  })  
  # print y value test
  output$text <- renderText({ 
  myreac <- myreac()
  paste("This is your output:",myreac)
  })  

Shiny UI

  shinyUI(fluidPage(
  titlePanel("New App"),  
  sidebarLayout(
  sidebarPanel(
  helpText("My App"),      
  selectInput("var", 
              label = "Choose an option:",
              choices = list("1", "2",
                             "3"),
              selected = "1"),
      ),

mainPanel(
  textOutput("text"),
  )   
 )
))  

The output I am getting: is basically blank:

This is your output:

Seems like nothing is output-ed by the reactive. Any help I could get will be much appreciated.

Upvotes: 1

Views: 1066

Answers (1)

Rorschach
Rorschach

Reputation: 32446

There are a couple of extra commas, but aside from that, if you convert x to numeric, it should work,

library(shiny)
shinyApp(
    shinyUI(fluidPage(
        titlePanel("New App"),  
        sidebarLayout(
            sidebarPanel(
                helpText("My App"),      
                selectInput("var", 
                            label = "Choose an option:",
                            choices = list("1", "2", "3"),
                            selected = "1")
            ),
            mainPanel(
                textOutput("text")
            )
        )
    )),
    shinyServer(function(input, output) { 
        myfunc <- function(x) as.numeric(x)+1
        myreac <- reactive({
            y <- myfunc(input$var)
            y
        })

        ## print y value test
        output$text <- renderText({ 
            myreac <- myreac()
            paste("This is your output:", myreac)
        })
    })
)

Upvotes: 1

Related Questions