require(shiny)
require(visNetwork)

server <- function(input, output) {

  output$network <- renderVisNetwork({
    nodes <- data.frame(id = 1:3)
    edges <- data.frame(from = c(1,2), to = c(1,3))

    visNetwork(nodes, edges) %>% visNodes(color = "green")
  })

  output$test <- renderPrint({
    input$network_positions
  })
  observe({
    input$goButton
    visNetworkProxy("network") %>%
      visGetPositions()
  })

}

ui <- fluidPage(
  fluidRow(
    column(10,visNetworkOutput("network", height = "100%"),
           verbatimTextOutput("test")),
    column(2, actionButton("goButton", "Go!"))
  )

)

shinyApp(ui = ui, server = server)

因此,visGetPositions仅适用于 Shiny 。按Go后,它将计算并打印出每个节点的位置。如何将其提取到R矩阵中,以便可以将其用作坐标?

最佳答案

一种可能是将坐标存储在reactiveValues中,并将它们与rbind绑定(bind)在一起。例如,将观察者替换为以下内容,

vals <- reactiveValues(coords=NULL)
observeEvent(input$goButton, {
  visNetworkProxy("network") %>% visGetPositions()
  vals$coords <- if (!is.null(input$network_positions))
                   do.call(rbind, input$network_positions)
})

它检查NULL,以便do.call不会出错。然后,output$test更改为以下内容以检查结果
output$test <- renderPrint( vals$coords )

更新

使用invalidateLater可以在没有按钮的情况下更新位置:
output$test <- renderPrint( vals$coords )
vals <- reactiveValues(coords=NULL)
observe({
  invalidateLater(1000)
  visNetworkProxy("network") %>% visGetPositions()
  vals$coords <- if (!is.null(input$network_positions))
                   do.call(rbind, input$network_positions)
})

关于r - visNetwork : How do I extract visGetPositions() from shiny into R coordinates matrix?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35961814/

10-12 23:26