如何简单地将变量从服务器传递到UI?

时间:2019-07-24 13:44:15

标签: r server shiny

我有一个闪亮的应用程序,其中服务器和用户界面位于两个不同的文件中。目的是显示网络图,因此我有一个节点列表和一个边列表。 我想添加一个允许用户选择某些节点的输入。

我的用户界面:

ui <- fluidPage(

      visNetworkOutput("network_proxy", height = "400px"), #Plot output
      selectInput(inputId = "selnodes", label = "Nodes selection", choices = , multiple = TRUE) #The input I want
)

我的服务器:

    nodes <- c(1, 5, 12, 53)
    edges <- data.frame(
       from = c(1,1,5,12,12,53), 
       to = c(5,12,12,12,53, 53),
       stringsAsFactors = FALSE)

    observeEvent(input$generatePlotButton,{
        net <<- generatePlot(nodes,edges)
        output$plotPlot <- renderVisNetwork({net})
    })

在用户界面的selectInput中,我希望建议的值成为我在绘图中使用的节点列表。因此,我在服务器上使用的变量nodes

但是,我不能简单地在参数中写入choices = nodes,因为UI不知道nodes是什么(请记住,它是服务器端的变量)。

因此,我想将nodes变量从服务器传递到UI,以便可以使用它在selectInput中将节点列表作为选择。

我该怎么办?预先感谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试:

ui <- fluidPage(

  visNetworkOutput("network_proxy", height = "400px"), #Plot output
  selectInput(inputId = "selnodes", label = "Nodes selection", choices = "", multiple = TRUE)
)

server <- function(input, output, session) {

  nodes <- c(1, 5, 12, 53)
  edges <- data.frame(
    from = c(1,1,5,12,12,53), 
    to = c(5,12,12,12,53, 53),
    stringsAsFactors = FALSE)

  observeEvent(input$generatePlotButton,{
    net <<- generatePlot(nodes,edges)
    output$plotPlot <- renderVisNetwork({net})
  })

  observe({
    updateSelectInput(session, "selnodes", choices = nodes)
  })

}

答案 1 :(得分:1)

另一种选择是使用renderUI将selectInput从服务器推送到ui,我喜欢使用它,因为从服务器数据集中提取选项更容易,并且您无需返回ui部分来更改代码。在下面的示例中,我没有使用updateSelectInput,因为在创建“全选”按钮时会更频繁地使用它。 这是我的代码:

library(shiny)
library(visNetwork)

ui <- fluidPage(
    visNetworkOutput("plotPlot", height = "400px"), #Plot output
    uiOutput("selnodes"),
    actionButton("Update", "Update")
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
    nodes <- data.frame(id = c(1, 5, 12, 53), label = c(1, 5, 12, 53))
    edges <- data.frame(
        from = c(1,1,5,12,12,53), 
        to = c(5,12,12,12,53, 53),
        stringsAsFactors = FALSE)

    output$selnodes <- renderUI({
        selectInput(inputId = "selnodes", label = "Nodes selection", choices = nodes, multiple = TRUE)
    })

    observeEvent(input$Update, {
        ## Update the nodes list 
        nodes <- data.frame(id = input$selnodes, label = input$selnodes)
        net <- visNetwork(nodes,edges)
        output$plotPlot <- renderVisNetwork({net})
    })
}

# Run the application 
shinyApp(ui = ui, server = server)
相关问题