James Willcox
James Willcox

Reputation: 631

use variable in UI of R Shiny?

I have created quite a large app that I now want to extent by introducing tabs. So far I have, as an example:

ui.R
shinyUI(
#OLD CODE
)

server.R
(
#OLD CODE
)

What I would like to do:

ui.R
shinyUI(
tabsetPanel(
"Tabs",
tabPanel("Old Code",value="tb1"),
tabPanel("New Code",value="tb2"),
id = "nlp"
),

if (id=="tb1") {
#OLD CODE
} else if (id=="tb2") {
#New Code 
} else {
#Do nothing
}

How do I get the if function to recognise id as a variable? When I run the script it comes up with the error object 'id' not found. So then I've tried input$id and output$id with no avail.

I have also tried going to the server.R and tried

Server.R
output$id <- renderText("id")

also didn't work when trying to bring that back into the UI

and I have also tried

Server.R
output$id <- reactive({input$id})

this also didn't work when I tried to use it in the UI. Where am I going wrong and how can I use the Id variable in the UI?

Thanks

Upvotes: 1

Views: 2029

Answers (1)

r2evans
r2evans

Reputation: 160447

Based on the Shiny Tabsets example, you should be putting the UI elements into each call to tabPanel, like so:

shinyUI(
    tabsetPanel(
        tabPanel(
            title = "Old Code",
            plotOutput('plot1'),
            plotOutput('plot2')
            ),
        tabPanel(
            title = "New Code",
            tableOutput('table')
            ),
        id = "nlp"
        )
    )

Unless you are trying to do more than necessary, your code does not need to know what tab the client has selected. I may be wrong (please do not think I'm an authority on shiny), I think the elements within the not-selected tabs are not unnecessarily recalculated (unless dependencies exist and require it).

Upvotes: 2

Related Questions