odar
odar

Reputation: 421

User defined function output in Shiny not in scope

I would like to use a user defined function in Shiny to perform a simple calculation with output two variables. The function I wrote works when it is not part of a shiny app. However when part of a Shiny, the returned object (dfr) is ‘not in scope’. What am I missing?

library(shiny)

# Function ----------------------------------------------------------------
convert <- function(coef_1, coef_2, vec) {
  part_1 <- coef_1/(2*sin((vec/2)*pi/180))
  part_2 <- 2*(180/pi)*(asin(coef_2/(2*part_1)))
  dfr <- data.frame(part_1, part_2)
  return(dfr)
}
# End Function ------------------------------------------------------------


ui <- fluidPage(
   sidebarLayout(
      sidebarPanel(
        textInput("num", h3("Enter number to convert:"), value = NULL)
      ),
      mainPanel(
        verbatimTextOutput("text1", placeholder = TRUE),
        verbatimTextOutput("text2", placeholder = TRUE)
      )
   )
)

server <- function(input, output) {

  nums_str <- as.character(input$num)
  nums_vector <- as.numeric(unlist(strsplit(nums_str, split = ",")))
  convert(1.5, 1.1, nums_vector)

  output$text1 <- renderText({
    req(input$num)
    dfr$part_1
    })

  output$text2 <- renderText({
    req(input$num)
    dfr$part_2
    })

}

shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 33

Answers (1)

bretauv
bretauv

Reputation: 8557

When you use inputs, you need to do it in reactive environment, such as reactive(), renderDataTable(), etc.

Here, you need to run your function in a reactive() and then call it with dfr() in the outputs.

server <- function(input, output) {

  dfr <- reactive({
    convert(1.5, 1.1, as.numeric(input$num))
  })

  output$text1 <- renderText({
    req(input$num)
    dfr()$part_1
  })

  output$text2 <- renderText({
    req(input$num)
    dfr()$part_2
  })

}

Since this is quite basic stuff with R Shiny, checking some tutorials might be very useful.

Upvotes: 2

Related Questions