Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

visNetwork: How do I extract visGetPositions() from shiny into R coordinates matrix?

Tags:

r

shiny

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)

So visGetPositions only works in shiny. After you press Go, it calculates and prints out positions of each node. How do I extract it into R matrix so I can use it as coordinates?

like image 576
James Avatar asked Oct 18 '22 13:10

James


1 Answers

One possibility would be storing the coordinates in a reactiveValues, binding them together with rbind. For example, replacing your observer with the following,

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

It checks for NULL so the do.call doesn't error. Then, the output$test changes to the following in order to check the result

output$test <- renderPrint( vals$coords )

update

A possible way to have the positions update without the button using 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)
})
like image 136
Rorschach Avatar answered Oct 28 '22 20:10

Rorschach