从 Shiny 中的列表对象中反应式提取数据

问题描述 投票:0回答:1

我正在尝试提取列表中存储的数据。我已经研究了基本的反应性,但现在我陷入困境,因为我不知道如何处理列表中的列表。

如果我运行该应用程序,我希望能够查看每个列表的底层数据帧。

例如,如果我在左侧的下拉列表中选择“output_2”,那么我希望看到页面右侧的数据框(从 2:20 开始)。

library(tidyverse)
library(shiny)
library(DT)

# create dummy data frames
df1.1 <- data.frame(Item = 1:10, Amount = 1:10)
df1.2 <- data.frame(Item = 1:10, Amount = 1:10)
df1.3 <- data.frame(Item = 1:10, Amount = 1:10)

df2.1 <- data.frame(Item = 2:20, Amount = 2:20)
df2.2 <- data.frame(Item = 2:20, Amount = 2:20)
df2.3 <- data.frame(Item = 2:20, Amount = 2:20)

df3.1 <- data.frame(Item = 3:30, Amount = 3:30)
df3.2 <- data.frame(Item = 3:30, Amount = 3:30)
df3.3 <- data.frame(Item = 3:30, Amount = 3:30)

# create list with dummy dfs
dummy_list1 <- list(df1.1 = df1.1,
                    df1.2 = df1.2,
                    df1.3 = df1.3)

dummy_list2 <- list(df2.1 = df2.1,
                    df2.2 = df2.2,
                    df2.3 = df2.3)

dummy_list3 <- list(df3.1 = df3.1,
                    df3.2 = df3.2,
                    df3.3 = df3.3)

# create data 
previous_data <- list(output_1 = dummy_list1,
                      output_2 = dummy_list2,
                      output_3 = dummy_list3)

previous_data_names <- previous_data %>% names()  

# Define UI for the app

ui <- fluidPage(
  titlePanel("Output Selector App"),
  sidebarLayout(
    sidebarPanel(
      selectInput("dataset", "Choose a dataset:", 
                  choices = previous_data_names)
    ),
    mainPanel(
      navlistPanel(
        tabPanel("df_1", dataTableOutput("df_1")),
        tabPanel("df_2", dataTableOutput("df_2")),
        tabPanel("df_3", dataTableOutput("df_3")),
      )
    )
  )
)


# Define server logic for the app
server <- function(input, output, session) {
  
  output$df_1 <- renderDataTable(
    datatable(df1.1)
  )
  
  output$df_2 <- renderDataTable(
    datatable(df1.2)
  )
  
  output$df_3 <- renderDataTable(
    datatable(df1.3)
  )
  
}


# Run the application
shinyApp(ui = ui, server = server)
r shiny shiny-reactivity
1个回答
0
投票

您需要在渲染函数中引用

previous_data
input$dataset

例如:

  output$df_1 <- renderDataTable(datatable(previous_data[[input$dataset][[1]]))
  output$df_2 <- renderDataTable(datatable(previous_data[[input$dataset][[2]]))
  output$df_3 <- renderDataTable(datatable(previous_data[[input$dataset][[3]]))
© www.soinside.com 2019 - 2024. All rights reserved.