polmath
polmath

Reputation: 335

In R shiny, how to use on the UI side a value computed on the SERVER side?

In my R shiny app, I would like to adjust the height of my d3heatmap (see package d3heatmap) as a function of the number of rows of my data frame; there is an argument height in the d3heatmapOutput to specify that.

However, my data frame is computed on the server side, so how can I pass its number of rows from the server side to the ui side?

Here is the example reflecting what I would like to do:

runApp(shinyApp(
  ui = fluidRow(
    selectInput("am", "Automatic (0) or manual (1) transmission?", 
                choices = c(0,1)), 

    # How can I have the 'height' argument equal to 'output$height'? 
    # I cannot use 'textOutput("height")' since it gives html code, not a value.
    d3heatmapOutput("heatmap", height = "400px") 
  ),
  server = function(input, output) {
    mtcars2 = reactive({
      mtcars[which(mtcars$am == input$am),]
    })
    output$height <- renderText({
      paste0(15*nrow(mtcars2()), "px")
    })
    output$heatmap <- renderD3heatmap({ 
      d3heatmap(mtcars2(), scale = "column") 
    })
  }
))

Thank you.

Upvotes: 3

Views: 681

Answers (1)

NicE
NicE

Reputation: 21425

You can use uiOutput in ui.R and renderUI in server.R to dynamically add the d3heatmapOutput:

library(shiny)
library(d3heatmap)
runApp(shinyApp(
  ui = fluidRow(
    selectInput("am", "Automatic (0) or manual (1) transmission?", 
                choices = c(0,1)), 

    uiOutput("ui_heatmap")

  ),
  server = function(input, output) {
    mtcars2 = reactive({
      mtcars[which(mtcars$am == input$am),]
    })
    output$ui_heatmap <- renderUI({
      d3heatmapOutput("heatmap", height = paste0(15*nrow(mtcars2()), "px")) 
    })    
    output$heatmap <- renderD3heatmap({ 
      d3heatmap(mtcars2(), scale = "column") 
    })

  }
))

You can then set the height of the heatmap in the server side of the app.

Upvotes: 3

Related Questions