Can we either print or plot in Shiny in same panel?

◇◆丶佛笑我妖孽 提交于 2021-01-28 20:43:44

问题


I would like to either call

 output$IPLMatchPlot <- renderPlot({ 

 f(x)

}) or

 output$IPLMatchPrint <- renderPrint({
   f(x)
 })

The function f(x) either returns a plot or a data frame.

I am able to do this separately in the server.R but would like to the display to be either a plot or the text of the data frame. Any suggestions of how to do this


回答1:


This can be handled by using a renderUI() which checks what kind of output it's getting and renders the appropriate output.

In the UI part you would place a uiOutput in the place where you want the plot or print to show up.

uiOutput("Plotorprint")

and then in the server you would define that uiOutput with something like this:

  output$Plotorprint <- renderUI({
    if (is.data.frame(f(x))) { # Check if output of f(x) is data.frame
      verbatinTextOutput("ISPLMatchPrint") # If so, create a print
    } else {                      # If not,
      plotOutput("ISPLMatchPlot") # create a plot
    }
  })

And you would keep the definitions you posted in your question in your server as well.

This should then check what output f(x) is getting, and render the appropriate output.




回答2:


The final code based on @Marjin's response is

server.R

output$IPLMatchPlot <- renderPlot({        
     f(x,y,z)


})
output$IPLMatchPrint <- renderPrint({        
    df <- f(x,y,z)
    df
})

output$plotOrPrint <-  renderUI({  
    if(is.data.frame(scorecard <- printOrPlot(input, output,teams, otherTeam))){
        verbatimTextOutput("IPLMatchPrint")
    }
    else{
        plotOutput("IPLMatchPlot")
    }
})

ui.R

 uiOutput("plotOrPrint"),


来源:https://stackoverflow.com/questions/41381466/can-we-either-print-or-plot-in-shiny-in-same-panel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!