0

我试图让用户选择他希望的显示类型,但是当我尝试渲染绘图时,它给了我一个错误。

这是代码:

library(shiny)
library(DT)
library(data.table)

runApp(list(
    ui = fluidPage(
        wellPanel(
            radioButtons("visuBtn", NULL, choices = c(Table = "table", Plot = "plot"))
        ),
        wellPanel(
            uiOutput("DataTable")
        )
    ),
    server = function(input, output){

        observeEvent(input$visuBtn,{
            output$DataTable <- renderUI({
                dfconc <- data.table(time = c(1,2,3,4,5), concentration = c(0.1, 0.4, 0.5, 0.7, 0.8))

                if(input$visuBtn == "table"){
                    output$aa <- renderDataTable(dfconc, options = list(paging = FALSE, searching = FALSE))
                    dataTableOutput("aa")
                }
                else { ### NOT WORKING
                    output$aa <- renderPlot({
                        plot(dfconc$time, dfconc$concentration, xlab = "Time", ylab = "Concentration")
                    })
                    fixedRow(
                        plotOutput("aa")
                    )
                }      ###

            })
        })
    }
))


谢谢你的帮助

4

2 回答 2

2

我认为如果您在客户端呈现输出然后简单地呈现show基于hide选择的元素会更好。这样你就不会浪费server资源

library(shiny)
library(shinyjs)
library(DT)
library(data.table)

runApp(list(
  ui = fluidPage(
    useShinyjs(),
    wellPanel(
      radioButtons("visuBtn", NULL, choices = c(Table = "table", Plot = "plot"))
    ),
    wellPanel(
      dataTableOutput("mytable"),
      plotOutput("myplot")
    )
  ),
  server = function(input, output, session){

    dfconc <- data.table(time = c(1,2,3,4,5), concentration = c(0.1, 0.4, 0.5, 0.7, 0.8))

    output$mytable <- renderDataTable(
      dfconc, options = list(paging = FALSE, searching = FALSE)
    )

    output$myplot <- renderPlot({
      plot(dfconc$time, dfconc$concentration, xlab = "Time", ylab = "Concentration")
    })

    observeEvent(input$visuBtn,{
      req(input$visuBtn)
      if(input$visuBtn == "plot"){
        hide("mytable")
        show("myplot")
      }else{
        hide("myplot")
        show("mytable")
      }
    })
  }
))
于 2019-11-27T12:20:36.153 回答
0

同意@Pork Chop。但为什么不简单地使用conditionalPanel

library(shiny)
library(DT)
library(data.table)

runApp(list(
  ui = fluidPage(
    wellPanel(
      radioButtons("visuBtn", NULL, choices = c(Table = "table", Plot = "plot"))
    ),

      conditionalPanel(
        condition = "input.visuBtn == 'table'",
        DTOutput('aa')
      ),
      conditionalPanel(
        condition = "input.visuBtn == 'plot'",
        plotOutput('bb')
      )

  ),
  server = function(input, output){
    dfconc <- data.table(time = c(1,2,3,4,5), concentration = c(0.1, 0.4, 0.5, 0.7, 0.8))

          output$aa <- renderDT(dfconc, options = list(paging = FALSE, searching = FALSE))
          output$bb <- renderPlot({
            plot(dfconc$time, dfconc$concentration, xlab = "Time", ylab = "Concentration")
          })
        } 

))
于 2019-11-27T12:31:00.203 回答