R visUpdateEdges:创建新边,而不是更新现有边

时间:2017-11-14 18:39:02

标签: r shiny visnetwork

我有一个动态网络,我想用R shiny和visNetwork代表。根据所选节点的不同,节点和边缘的颜色应根据一些外部协议/数据(下面代码中的nodeslist& edgeslist)进行更改。

这对节点非常有效:我选择一个节点,在以后的所有时间步骤中,节点的颜色会根据数据而变化。为此,我使用visUpdateNodes

但是当我尝试对visUpdateEdges的边缘基本相同时,它无法正常工作:不是仅对节点着色,而是创建新节点(使用正确的颜色)。

这里有一个简单的例子:

library(shiny)
library(tidyverse)
library(visNetwork)

# some data - these values are for the updating process
nodeslist <- list(id1 = data_frame(R1 = c("red", "orange", "orange"), R2 = c("red", 
  "black", "green"), R3 = c("red", "cyan", "yellow")), id2 = data_frame(R1 = c("orange", 
  "red", "orange"), R2 = c("black", "red", "green"), R3 = c("orange", "red", 
  "yellow")), id3 = data_frame(R1 = c("orange", "orange", "red"), R2 = c("black", 
  "yellow", "red"), R3 = c("brown", "cyan", "red")))

edgeslist <- list(id1 = data_frame(R1 = c("red", "orange", "orange"), R2 = c("red", 
  "black", "green"), R3 = rep("black", 3)), id2 = data_frame(R1 = c("orange", 
  "red", "orange"), R2 = c("black", "red", "green"), R3 = rep("black", 3)), 
  id3 = data_frame(R1 = c("orange", "orange", "red"), R2 = c("black", "yellow", 
    "red"), R3 = rep("black", 3)))

# the updating functions
changeColorOfOtherNodes <- function(nodes, selected.node, index) {
  nodes %>% mutate(color = unlist(nodeslist[[as.numeric(selected.node)]][, 
    index]))
}

changeColorOfEdges <- function(edges, selected.node, index) {
  edges %>% mutate(color = unlist(edgeslist[[as.numeric(selected.node)]][, 
    index]))
}


# making the network
id <- c(1, 2, 3)
color <- rep("cyan", length(id))
nodes <- data_frame(id, color)

from <- c(1, 2, 3)
to <- c(2, 3, 1)
edges <- data_frame(from, to, color = rep("#333333", 3), value = c(2, 2, 2))



# shiny application
server <- shinyServer(function(input, output, session) {

  output$netplot <- renderVisNetwork({
    visNetwork(nodes, edges) %>% visOptions(nodesIdSelection = list(enabled = TRUE))
  })

  observe({
    if (!is.null(input$netplot_selected) && input$netplot_selected > 0) {

      for (i in 1:ncol(nodeslist[[as.numeric(input$netplot_selected)]])) {

        # updating works well for nodes
        nodes <- changeColorOfOtherNodes(nodes, input$netplot_selected, 
          index = i)
        visNetworkProxy("netplot") %>% visUpdateNodes(nodes)
        Sys.sleep(1)
        # updating for edges -> new edges are creates, but don't know why
        edges <- changeColorOfEdges(edges, input$netplot_selected, index = i)
        visNetworkProxy("netplot") %>% visUpdateEdges(edges)
        Sys.sleep(1)
        print(edges)
      }

    }
  })

})


ui <- shinyUI(fluidPage(mainPanel(visNetworkOutput("netplot"))))
shinyApp(server = server, ui = ui)

有谁知道如何正确更新visUpdateEdges节点的颜色?为什么visUpdateEdges创建新边缘而不是更新现有边缘?

1 个答案:

答案 0 :(得分:1)

您必须在边id设置data.frame,因此请使用它来引用visUpdateEdges中的现有边

edge <- data.frame(id = 1:3, from = ....)
# update color of edge 1
visUpdateEdges(data.frame(id = 1, color = "red"))