列表列表中的 R Shiny Reactive Plot

R Shiny Reactive Plot from List of Lists

我正在构建一个基本的 R Shiny 应用程序,并且有一个包含单独列表的列表,每个列表存储一个数据框和一个值。我已经包含示例数据来演示我的列表列表。在我的应用程序中,我试图有一个 select 选项(一个显示“列表 1”、列表 2”等的下拉菜单),然后让应用程序中的主面板显示数据框的箱线图(x 和y) 和存储在 selected.

列表中的值的文本输出

我无法使输出(绘图和文本)对来自 selected 列表的输入和显示数据作出反应。

我已经把我到目前为止的代码放在下面了。

## Example Data
list_a <- list(df = data.frame(x = rnorm(n = 10, mean = 5, sd = 2),
                             y = rnorm(n = 10, mean = 7, sd = 3)),
             value = "a")
list_b <- list(df = data.frame(x = rnorm(n = 10, mean = 20, sd = 5),
                             y = rnorm(n = 10, mean = 13, sd = 7)),
             value = "b")
list_c <- list(df = data.frame(x = rnorm(n = 10, mean = 12, sd = 4),
                             y = rnorm(n = 10, mean = 10, sd = 4)),
             value = "c")

mylist <- list(list_a, list_b, list_c)

## Packages
library(tidyverse)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Shiny App"),

## Panel with selectInput dropdown and output options
    pageWithSidebar(
        headerPanel('Data'),
        sidebarPanel(
            selectInput('data', 'Dataset',
                        choices = c("1" = list_a, "2" = list_b, "3" = list_c)),
        ),
        mainPanel(
            plotOutput('plot1'),
            textOutput('text1')
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    ## Boxplot with 'DF' from selected list
        output$plot1 <- renderPlot({
        reactivedata <- boxplot(input$data)
        boxplot(reactivedata$df)
    })

    ## Text output from 'value' stored in list
    output$text1 <- renderText({
        reactivetext <- print(input$data)
        print(reactivetext$value)
    })


}

# Run the application
shinyApp(ui = ui, server = server)

您的代码的主要问题是您将原始列表用于 choices 参数。此外,我添加了一个 reactive 以根据用户的输入选择正确的列表:

set.seed(123)

library(tidyverse)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Shiny App"),

  ## Panel with selectInput dropdown and output options
  pageWithSidebar(
    headerPanel("Data"),
    sidebarPanel(
      selectInput("data", "Dataset",
        choices = c("list_a" = 1, "list_b" = 2, "list_c" = 3)
      ),
    ),
    mainPanel(
      plotOutput("plot1"),
      textOutput("text1")
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

  reactivedata <- reactive({
    mylist[[as.integer(input$data)]]  
  })
  
  ## Boxplot with 'DF' from selected list
  output$plot1 <- renderPlot({
    boxplot(reactivedata()$df)
  })

  ## Text output from 'value' stored in list
  output$text1 <- renderText({
    print(reactivedata()$value)
  })
}

# Run the application
shinyApp(ui = ui, server = server)
#> 
#> Listening on http://127.0.0.1:4502
#> [1] "a"