Reputation: 33
I'm trying to build my first Shiny app at the moment and and having some issues. Is it possible to get access to a variable from a different output object? I'm trying to print the table in the first tab and show the individual plots on separate tabs, even better if I can show all 3 on 1 tab.
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Table", tableOutput("dataTable")),
tabPanel("xy Chart", plotOutput("xyChart")),
tabPanel("yz Chart", plotOutput("yzChart"))
)
)
)
)
)
server <- function(input, output) {
output$dataTable <- renderTable({
x <- rnorm(100, mean = 1)
y <- rnorm(100, mean = 0)
z <- rnorm(100, mean = 0.5)
dataTable <- cbind(x,y,z)
})
output$xyChart <- renderPlot({
plot(x,y)
})
Upvotes: 3
Views: 1309
Reputation: 30474
If you haven't already, would take a look at the shiny
tutorials available.
Instead of including your data in a single output
inside of server
, you could declare these variables elsewhere. Since you are creating a shiny
app, you might be interested in changing these variables, and having the other outputs
automatically update.
If that is true, you might want to use reactiveValues
or create a reactive
function.
Here's an example below. By using reactiveValues
, when you read a value from it (like x, y, or z) the calling expression takes a reactive dependency on that value (and will update with changes made to it). Whenever you modify those values, it will notify all reactive functions that depend on that value.
library(shiny)
ui <- fluidPage(
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Plot", plotOutput("plot")),
tabPanel("Summary", verbatimTextOutput("summary")),
tabPanel("Table", tableOutput("table"))
)
)
)
server <- function(input, output) {
my_data <- reactiveValues(
x = rnorm(100, mean = 1),
y = rnorm(100, mean = 0),
z = rnorm(100, mean = 0.5)
)
output$table <- renderTable({
data.frame(my_data$x, my_data$y, my_data$z)
})
output$plot <- renderPlot({
plot(my_data$x, my_data$y)
})
output$summary <- renderText({
"Summary Goes Here"
})
}
shinyApp(ui = ui, server = server)
And if you want all 3 on one panel (as described in comments), use this for your ui
:
ui <- fluidPage(
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("All 3",
plotOutput("plot"),
verbatimTextOutput("summary"),
tableOutput("table")
)
)
)
)
If you want to include your input$nRV
(as mentioned in comments), use a reactive
expression, and call it as my_data()
:
server <- function(input, output) {
my_data <- reactive({
a = rnorm(input$nRV, mean = 2)
b = rnorm(input$nRV, mean = 5)
x = rnorm(input$nRV, mean = 3)
y = rnorm(input$nRV, mean = 0)
z = rnorm(input$nRV, mean = 0.5)
data.frame(a, b, x, y, z)
})
output$table <- renderTable({ data.frame(my_data()$x, my_data()$y, my_data()$z)
})
output$plot <- renderPlot({ plot(my_data()$x, my_data()$y) })
}
Upvotes: 3