Reputation: 981
I built the shiny app below that updates the line graph based on the user's input. It works fine until I try to generate a 2nd output. How can I display the value total.weight
calculated in the renderPlot()
function? It seems to me my data set df
and the variable total.weight
should be created "outside" of the renderPlot()
function but I have not figured out how.
ui.r
library(shiny)
shinyUI(fluidPage(
# Application title
titlePanel("Reproducible Example"),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
selectInput("ID", "group", c("A", "B"))
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("plot1"),
verbatimTextOutput("text1")
)
)
))
server.r
library(shiny)
library(ggplot2)
shinyServer(function(input, output) {
output$plot1 <- renderPlot({
years <- c(1:10)
weight <- c(5,7,9,11,12,17,19,20,21,22)
group <- c(rep("A",5), rep("B",5))
df <- data.frame(years,weight,group)
df <- subset(df, group == input$ID)
total.weight <- sum(df$weight)
#Plot
ggplot(data=df, aes(x=df$years, y=df$weight)) +
geom_line() +
geom_point()
})
output$text1 <- renderText({total.weight})
})
Upvotes: 0
Views: 56
Reputation: 3250
You can also create reactives:
server.R
library(shiny)
library(ggplot2)
shinyServer(function(input, output) {
df <- reactive({
years <- c(1:10)
weight <- c(5,7,9,11,12,17,19,20,21,22)
group <- c(rep("A",5), rep("B",5))
df <- data.frame(years,weight,group)
df <- subset(df, group == input$ID)
})
total.weight <- reactive({
sum(df()$weight)
})
output$plot1 <- renderPlot({
#Plot
ggplot(data=df(), aes(x=years, y=weight)) +
geom_line() +
geom_point()
})
output$text1 <- renderText({total.weight()})
})
Upvotes: 1
Reputation: 19544
The quick workaround is to put the total weight in a global varaiable:
total.weight <<- sum(df$weight)
The nice way to do it is to subset your data.frame within a reactive
function:
shinyServer(function(input, output) {
years <- c(1:10)
weight <- c(5,7,9,11,12,17,19,20,21,22)
group <- c(rep("A",5), rep("B",5))
df <- data.frame(years,weight,group)
reactive_df <- reactive(subset(df, group == input$ID))
output$plot1 <- renderPlot({
ggplot(data=reactive_df(), aes(x=years, y=weight)) +
geom_line() +
geom_point()
})
output$text1 <- renderText({sum(reactive_df()$weight)})
})
Upvotes: 1