这篇文章是对前一篇文章的扩展,其中提供的答案非常适合。然而,我想通过动态分配列表项目名称,使用unique(iris$Species)
中的值而不是硬编码命名列表中的项目,使应用程序更加灵活。我试图通过一个for循环来分配命名列表中的项目:for (m in species_list){ paste0("species_",m) = species_table[[m]]}
。然而,当我运行应用程序时,我得到一个错误说"下标越界"。我在下面包含了完整的可复制示例:
data(iris)
ui <- fluidPage(
mainPanel(
fluidRow(selectInput("portfolio", label = "Select Species", choices = unique(iris$Species))),
fluidRow(tableOutput("result"))
)
)
server <- function(input, output) {
species_list <- unique(iris$Species)
species_function <- reactive({
species_table <- list()
for (i in reactiveValuesToList(species_list)){
local({
j <- i
species_table[[j]] <<- iris[iris$Species==j,]
})
}
return(list(
for (m in species_list){
paste0("species_",m) = species_table[[m]]
}
))
})
output$result <- renderTable({
input$portfolio
species_table2 <- list()
for (p in reactiveValuesToList(species_list)){
local({
q <- p
species_table2[[reactive({q})()]] <<- species_function()[[paste0("species_",reactive({q})())]][1:5, c("Sepal.Length", "Sepal.Width")]
})
}
print(species_table2[[input$portfolio]])
return(species_table2[[input$portfolio]])
})
}
shinyApp(ui = ui, server = server)```
以下修改后的代码,结合了@MrFlick的反馈,并将species_list指定为响应值,功能如预期。
library(shiny)
data(iris)
ui <- fluidPage(
mainPanel(
fluidRow(selectInput("portfolio", label = "Select Species", choices = unique(iris$Species))),
fluidRow(tableOutput("result"))
)
)
server <- function(input, output) {
species_names <- as.character(unique(iris$Species))
species_list <- reactiveValues()
for(i in 1:length(species_names)) {
species_list[[paste0("species_", i)]] <- species_names[[i]]
}
species_function <- reactive({
species_table <- list()
for (i in reactiveValuesToList(species_list)){
local({
j <- i
species_table[[j]] <<- iris[iris$Species==j,]
})
}
setNames(species_table, species_names)
})
output$result <- renderTable({
input$portfolio
species_table2 <- list()
for (p in reactiveValuesToList(species_list)){
local({
q <- p
species_table2[[reactive({q})()]] <<- species_function()[[reactive({q})()]][1:5, c("Sepal.Length", "Sepal.Width")]
})
}
return(species_table2[[input$portfolio]])
})
}
shinyApp(ui = ui, server = server)