Search code examples
rtextanalysisnetworkd3

Add an Vertex Attribute to NetworkD3 object


Greeting folks,

I have been struggling with adding a colour group to a object in for the purpose of a network visual. The code to render the visual is stable but I currently have the grouping variable set to 1. The tricky bit is that I have a separate table for which I am using to evaluate a colour group.

I tried to add it as a vector by first generating a list.

V(network)$color <- group[V(network)$name]

I have also tried a custom function called makeVertexAtt as well as using set_vertex_attr and vertex_attr-set from but to no avail. The issue I get in doing a simple join within a network object is cannot coerce class ‘"igraph.vs"’ to a data.frame. Fair enough, but if I create the vector and add it in I get Not a graph object errors.

Let's say for example (since this is not a graph object) I have this vector of names:

V(Graph)$names<-c("knife","kitchen","toilet","shower","toothbrush", "shed")

I then have a separate data set that has two columns, the word and the category.

Word<-c("knife","kitchen","toilet","shower","toothbrush")
Category <-c("Kitchen","Kitchen","bathroom","bathroom","bathroom")

I would ideally want a V(graph)$color attribute that has a matching vector

V(graph)$color<-c("Kitchen","Kitchen","bathroom","bathroom","bathroom","N/A")

Any ideas would be appreciated.


Solution

  • here's an easy way to merge group information from one data frame to your nodes data frame

    names <- c("knife", "kitchen", "toilet", "shower", "toothbrush", "shed")
    nodes <- data.frame(names, stringsAsFactors = FALSE)
    
    Word <- c("knife", "kitchen", "toilet", "shower", "toothbrush")
    Category <- c("Kitchen", "Kitchen", "bathroom", "bathroom", "bathroom")
    group <- data.frame(Word, Category, stringsAsFactors = FALSE)
    
    nodes$group <- group$Category[match(nodes$names, group$Word)]
    
    nodes
    #       names    group
    # 1      knife  Kitchen
    # 2    kitchen  Kitchen
    # 3     toilet bathroom
    # 4     shower bathroom
    # 5 toothbrush bathroom
    # 6       shed     <NA>