Daniele Avancini
Daniele Avancini

Reputation: 979

conditional RenderUI R shiny

I have a problem with renderUI and I couldn't find a solution anywhere. Probably I'm asking the wrong question to google and more than a shiny problem is a basic R problem.

I have a function in R which depending on the input will return a table or a text. So I created both the options in my server.R in this way:

output$table <- renderTable {(
   x <- function (y)
   print(x)
)}
output$text <- renderText {(
   x <- function (y)
   print(x)
)}

If I put both the outputs in renderUI one will always give me an error. In case of textOutput if the output is a table:

 Error: argument 1 (type 'list') cannot be handled by 'cat'

and

 Error:no applicable method for 'xtable' applied to an object of class "character"

if it is viceversa.

My question is there a way to catch this error and use an if statement within renderUI to display only one of the two? I'm here to give you more details if you need.

[EDIT]

server.R

 library(shiny)
 library(drsmooth)

 shinyServer(function(input, output,session) {

-- upload dataframe and input management goes here --

 output$nlbcd <- renderTable({
    nlbcd<-nlbcd(dosecolumn="Dose", targetcolumn=response(),cutoffdose=cutoff(),data=data1())
    print(nlbcd)
 })

 output$nlbcdText <- renderText({
    nlbcd<-nlbcd(dosecolumn="Dose", targetcolumn=response(),cutoffdose=cutoff(),data=data1())
   print(nlbcd)
 }) 

 output$tb <- renderUI({
 tableOutput("nlbcd"),
 textOutput("nlbcdText")   
})

})

Upvotes: 3

Views: 3082

Answers (2)

mlegge
mlegge

Reputation: 6913

You have some issues here, the function will return different classes, including errors and warnings with interpretations. Here is a standalone example of what can happen with this function, you are encouraged to include the TryCatch in your code:

ui.R

shinyUI(
  pageWithSidebar(   
    headerPanel("drsmooth"),   sidebarPanel(
      numericInput("num", label = h3("Choose 'cutoffdose'"), value = 0)
    ),
    mainPanel(
      verbatimTextOutput('current')
    ) 
  )
)

server.R

library(drsmooth)

shinyServer(function(input, output, session) {
 output$current <- renderPrint({
   dose <- input$num

   tryCatch(isolate(nlbcd("dose", "MF_Log", cutoffdose=dose, data=DRdata)), 
            error=function(e) {
              cat(isolate(conditionMessage(e)))
            }
   )

 })
})

Sample outputs: With <code>cuttoffdose</code>= 0

With <code>cutoffdose</code>= 1

With <code>cutoffdose</code>= 1.5

Upvotes: 2

Mikael Jumppanen
Mikael Jumppanen

Reputation: 2486

I would try to use function class().

output$table <- renderTable {(
   x <- function (y)
   if(class(x) == "table")
     print(x)

)}
output$text <- renderText {(
   x <- function (y)
   if(class(x) == "list")
     print(x)
)}

Upvotes: 0

Related Questions