在Shiny中使用字符串变量作为列名

时间:2016-12-06 17:12:19

标签: r 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() })

})

如果ui.R更改为

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)

  )))

这是所需的产品:

enter image description here

目标:声明一个字符串变量,其值 NOT 来自用户的结尾(这将在R代码中手动更改),所以每当CYR值改变时,UI都会更新。无论此变量是在ui.R还是server.R。

中声明都无关紧要

1 个答案:

答案 0 :(得分:1)

看起来renderUI就是您所需要的。另请注意,您的substr不正确我已将其修复

#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