R Shiny保持标题和文本框更新

时间:2016-03-08 21:28:45

标签: r shiny

在一个Shiny应用程序中,我希望每次用户更改打印类型时标题都是默认标题,但我希望用户能够手动更改文本框中的值并更新打印标题。基本上这相当于:

规则

1)每次用户在下拉菜单中更改绘图类型时,请使用默认标题并使用标题更新文本框。

2)每次用户在文本框中进行更改时,请使用文本框中的文本替换标题。

举个例子:

1)如果用户选择绘图类型“n”,则标题将为“Plot type is n”,文本框将相同。

2)然后,如果用户键入文本框“Blah,blah”,则情节标题变为“Blah blah”。

3)然后当用户将绘图类型更改为“p”时,标题变为“Plot type is p”

等等,建议?

library(shiny)

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

  output$plot <- renderUI({

    h <- input$height
    w <- input$width
    list(
      tags$h3("Plot information"),
      renderPlot({

        # if input$title has been changed by the user update the
        # plot title to input$title, otherwise use default_title

        default_title <- paste("Plot type is", input$type)
        updateTextInput(session, "title", value=default_title)
        plot(1:10, main=default_title, type=input$type)

      })
    )
  })

} 

ui <- fluidPage(
  tags$div(class="panel-body",

           textInput("title", "Give a title",  "This is my initital title"),
           selectInput("type", "choose type", choices=c("p", "n", "s"), selected="s")
  ),

  uiOutput("plot")

)

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:0)

以下代码应该有效。我将逻辑分为两个不同的observe

library(shiny)

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

  # This updates both the text input and the plot when type changes
  observe({
    type <- input$type
    default_title <- paste("Plot type is", input$type)
    updateTextInput(session, "title", value = default_title)
    output$plot <- renderPlot({
      plot(1:10, main = default_title, type = input$type)
    })
  })

  # This updates the plot when input changes
  observe({
    title <- input$title
    output$plot <- renderPlot({
      plot(1:10, main = title, type = input$type)
    })
  })

  output$plotInfo <- renderUI({
    list(tags$h3("Plot information"))
  })

}


ui <- fluidPage(

  tags$div(
    class = "panel-body",
    textInput("title", "Give a title",  "This is my initital title"),
    selectInput(
      "type",
      "choose type",
      choices = c("p", "n", "s"),
      selected = "s"
    )
  ),

  uiOutput("plotInfo"),
  plotOutput("plot")

)

shinyApp(ui = ui, server = server)
相关问题