渲染2输出引用相同的数据集

时间:2016-11-28 20:40:34

标签: r shiny

我在下面构建了闪亮的应用程序,根据用户的输入更新了折线图。它工作正常,直到我尝试生成第二个输出。如何显示total.weight函数中计算的值renderPlot()?在我看来,我的数据集df和变量total.weight应该创建"外部" renderPlot()函数,但我还没弄明白。

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})

})

输出快照: enter image description here

2 个答案:

答案 0 :(得分:1)

快速解决方法是将总权重置于全局变量中:

total.weight <<- sum(df$weight)

这样做的好方法是在reactive函数中对data.frame进行子集化:

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)})

})

答案 1 :(得分:1)

您还可以创建被动反应:

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()})

    })