Clarinetist
Clarinetist

Reputation: 1187

Using a string variable for a column name in Shiny

ui.R:

library(shiny)
shinyUI(  fluidPage(fluidRow(
    column(input$PYR,
         style = 'padding:25px',
         textInput("N_PYR", NULL, width = '192px'),
         textInput("RATE_PYR", NULL, width = '192px'),
         width = 3),
    column(input$CYR,
           style = 'padding:25px',
           textInput("N_CYR", NULL, width = '192px'),
           textInput("RATE_CYR", NULL, width = '192px'),
           width = 3)

  )))

server.R:

library(shiny)
shinyServer(function(input, output, session) {
  # current year ("2015-16" for example)
  input$CYR <- reactive({"2015-16"})

  input$PYR <- reactive({paste0(
    as.numeric(substr(input$CYR, start = 1, stop = 4)-1),
    "-",
    as.numeric(substr(input$CYR, start = 6, stop = 7)-1))
    })

  # terminate when window is closed
  session$onSessionEnded(function() { stopApp() })

})

If ui.R is changed to

library(shiny)
shinyUI(  fluidPage(fluidRow(
    column("2014-15",
         style = 'padding:25px',
         textInput("N_PYR", NULL, width = '192px'),
         textInput("RATE_PYR", NULL, width = '192px'),
         width = 3),
    column("2015-16",
           style = 'padding:25px',
           textInput("N_CYR", NULL, width = '192px'),
           textInput("RATE_CYR", NULL, width = '192px'),
           width = 3)

  )))

this is the desired product:

enter image description here

Goal: declare a string variable whose value will NOT be given from the user's end (this will be manually changed in the R code), so that the UI is updated whenever the CYR value is changed. It does not matter whether this variable is declared in ui.R or server.R.

Upvotes: 0

Views: 598

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

Looks like renderUI is all you need. Also note that your substr was incorrect I fixed it

#rm(list = ls())
library(shiny)
ui <- fluidPage(uiOutput("ui1"))

server <- function(input, output, session) {
  # current year ("2015-16" for example)
  CYR <- reactive({"2015-16"})
  PYR <- reactive({
    paste0(
      as.numeric(substr(CYR(), start = 1, stop = 4))-1,
      "-",
      as.numeric(substr(CYR(), start = 6, stop = 7))-1)
  })

  output$ui1 <- renderUI({
    fluidRow(
    column(PYR(),
           style = 'padding:25px',
           textInput("N_PYR", NULL, width = '192px'),
           textInput("RATE_PYR", NULL, width = '192px'),
           width = 3),
    column(CYR(),
           style = 'padding:25px',
           textInput("N_CYR", NULL, width = '192px'),
           textInput("RATE_CYR", NULL, width = '192px'),
           width = 3))
  })
  # terminate when window is closed
  session$onSessionEnded(function() { stopApp() })
}

shinyApp(ui, server)

enter image description here

Upvotes: 1

Related Questions