Slownz
Slownz

Reputation: 145

Shiny in R: send numeric value to UI from Server

I would like send numeric value to ui.r from the server.r

For example when I load a database to the server side, I would like to send length(colnames(datababase)) to the UI.

It is important to send as a numeric value because I would like to make some calculations with it on the UI side.

How can I do it?

I know there are some solutions like textOutput which communicates with the UI, but now I would like to pass numeric value.

ps1: as.numeric(textOutput("text1')) does not works. :)

ps2: I also know the function sendCustomMessage and Shiny.addCustomMessageHandler but I dont really understand how can I use it to send information directly to the UI.

Upvotes: 0

Views: 2159

Answers (2)

Alexvonrass
Alexvonrass

Reputation: 330

If i understood your problem correctly you need to take a look at observeEvent and reactive values, so that your plot re-renders every time an input is changed (or some other event occurs)

Basically in your server.R there's a call to renderPlot inside of observeEvent, you don't actually have to "send" it to UI (again, if i understood what you meant, it's hard to say for sure without an example)

Upvotes: 1

Tonio Liebrand
Tonio Liebrand

Reputation: 17719

I would recommend a solution with renderUI()anyway :).

library(shiny)

ui <- fluidPage(
  selectInput("nr", "number", 2:4),
  uiOutput("plots")
)

server <- function(input, output, session) {

  output$plots <- renderUI({
    plot_output_list <- lapply(1:input$nr, function(i) {
      plotname <- paste0("plot", i)
      plotOutput(plotname)
    })
    tagList(plot_output_list)
  })

  observe({
    for(iterNr in 1:input$nr){
      output[[paste0("plot", iterNr)]] <- renderPlot({
        plot(iterNr)
      })
    }
  })
}

shinyApp(ui, server)

Upvotes: 2

Related Questions