【发布时间】:2021-07-29 13:09:56
【问题描述】:
这是我第一次创建仪表板,我遇到了一个我似乎无法解决的问题。我创建了一个 sankey 图,我希望能够通过不同的数据框(在本例中:level_1、level_2、level_3)以交互方式更改其内容。我只用常规图练习过这个,其中输入来自一个数据框中的变量,这是我在这段代码中的起点(例如,我有一个 df$country,所以我在我的plot --> 然后我可以在仪表板侧边栏中选择不同的国家,以更改情节的内容)。当输入必须来自单独的数据帧时,我不知道该怎么做。
我的代码:(在 app.R 中)
level_1 <- as.data.frame(matrix(sample(seq(0,40), 15, replace=T ), 3, 5))
level_2 <- as.data.frame(matrix(sample(seq(0,40), 20, replace=T ), 4, 5))
level_3 <- as.data.frame(matrix(sample(seq(0,40), 25, replace=T ), 5, 5))
levels <- list(level_1, level_2, level_3)
ui <- dashboardPage(
dashboardHeader(title = "title"),
dashboardSidebar(
selectInput("in_levels", "Levels", choices = levels)
),
dashboardBody(
fluidRow(sankeyNetworkOutput("widget1"))
)
)
server <- function(input, output) {
links <- input$in_levels %>%
rownames_to_column(var="source") %>%
gather(key="target", value="value", -1) %>%
filter(value != 0)
nodes <- data.frame(
name=c(as.character(links$source), as.character(links$target)) %>%
unique()
)
links$IDsource <- match(links$source, nodes$name)-1
links$IDtarget <- match(links$target, nodes$name)-1
output$widget1 <- renderSankeyNetwork({
sankeyNetwork(Links = links, Nodes = nodes,
Source = "IDsource", Target = "IDtarget",
Value = "value", NodeID = "name", fontSize = 14, nodeWidth = 60,
fontFamily = "Arial", iterations = 0, sinksRight=TRUE)
})
}
shinyApp(ui, server)
我认为创建所有数据框的 list()、levels 可能会有所帮助,但这不起作用。我收到此错误:
Error : Can't access reactive value 'in_levels' outside of reactive consumer.
i Do you need to wrap inside reactive() or observer()?
我搜索了 reactive() 和 observer() 以尝试找出我的下一步应该是什么,但我还没有找到解决方案。如果有人可以就如何进行、进行更改或阅读一些内容以增加我的理解提供建议,我将不胜感激。
提前致谢!
【问题讨论】:
-
您不能在
selectInput的choices参数中使用数据帧列表。您可以先执行levels <- list(data1=level_1, data2=level_2, data3=level_3),然后执行choices = c("data1", "data2", "data3"),然后在server中使用levels[[input$in_levels]]获得选定的数据框。 -
谢谢@StéphaneLaurent,这非常有帮助!
标签: r shiny shinydashboard shiny-reactivity