动态分配值使用循环的列表
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)```
This post is an extension of a previous post for which the answer provided was perfectly suitable. However, I'd like to make the app more flexible by assigning the list item names dynamically, using the values in unique(iris$Species)
instead of hard coding the items in the named list. I've tried to do this by assigning the items in the named list via a for loop: for (m in species_list){ paste0("species_",m) = species_table[[m]]}
. However, when I run the app I get a error saying "subscript out of bounds". I've included the complete replicable example below:
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)```
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下修改的代码,将@mrflick的反馈和将物种_list指定为反应性值,符合预期的功能。
The following modified code, incorporating feedback from @MrFlick and specifying species_list as a reactive value, functions as expected.