在Rshiny中,在renderPlot和renderText之间切换

时间:2017-03-01 19:14:02

标签: r ggplot2 shiny

首先,这是我的Rshiny应用程序的一个被剥离的骨架,我正在尝试做什么(但是失败了):

ui <- shinyUI(fluidPage(
  titlePanel("Player Self-Centered Rating"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("radio", label = h3("Chart Type"),
                   choices = list("RadarPlot" = 1, 
                                  "Separate Plots" = 2, 
                                  "Top / Bottom 5 Table" = 3), 
                   selected = 1)

    mainPanel(
      plotOutput('radarPlot', width = 50),
      textOutput("text2")
    )
  )
))

server <- shinyServer(function(input, output) {
  if (input$radio %in% c(1,2)) {
      output$radarPlot <- renderPlot({          
      ggplot(data, aes(x = reorder(names, -ft_per_min), y = ft_per_min, col = this_player, fill = this_player)) +
        geom_bar(stat = "identity")

      }
    }, height = 800, width = 900)
  }
  else if(input$radio == 3) {      
    output$text2 <- renderText({ 
      paste("print some text")
    })
  }
})

这种使用if和if / else情况确定是否调用renderPlot或renderText的方法不起作用。我收到这个错误:

Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

我在这里尝试做什么?任何关于错误的想法,以及我是否需要这种反应性表达都将不胜感激!

1 个答案:

答案 0 :(得分:1)

input$..值只能在reactiverender*函数内进行评估。

你可以这样做:

ui <- shinyUI(fluidPage(
  titlePanel("Player Self-Centered Rating"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("radio", label = h3("Chart Type"),
                   choices = list("RadarPlot" = 1, 
                                  "Separate Plots" = 2, 
                                  "Top / Bottom 5 Table" = 3), 
                   selected = 1)),
    mainPanel(
      plotOutput('radarPlot', width = 50),
      textOutput("text2")
    )
  )
))

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

  output$radarPlot <- renderPlot({
    if (input$radio %in% c(1,2)) {
      ggplot(mtcars, aes(x = mpg, y = cyl, col = hp, fill = hp)) +
        geom_bar(stat = "identity")}
  }, height = 800, width = 900)

  output$text2 <- renderText({
    if (input$radio == 3) {
      paste("print some text")}
  })

})

shinyApp(ui,server)