Add attributes (sex) to vertex in edgelist

I have an edgelist of reproductive pairs as follows:

male_ID=c(1,2,3,4,5), female_ID=c(6,7,8,9,10), a=cbind(male_ID, female_ID)

using Igraph I generated a graph from the data, to plot and run some analysis on the full df:

g <- graph_from_data_frame(a)

My question is, can I now add an attribute (to colour vertices) for the sex of the individual, based on the column they are listed in the edgelist?

Asked on August 30, 2020 in R.
Add Comment
1 Answer(s)

you can assign group labels to your graph object.

For creating the group vector ‘sex’, your dataframe suggests that you have as many male as female persons. graph_from_data_frame() stacks the mal_ID and female_ID columns below each other which you can check with igraph::V(g). Hence you can derive the group vector from that information:

 male_ID=c(1,2,3,4,5); female_ID=c(6,7,8,9,10); a=cbind(male_ID, female_ID)  #create graph object from dataframe g <- igraph::graph_from_data_frame(a)  #investigate structure g igraph::V(g) #[1] 1  2  3  4  5  6  7  8  9  10  # create sex group vector sex <- c(replicate(length(male_ID), "Male"), replicate(length(female_ID), "Female"))  #Check group values print(igraph::V(g)$group) # NULL  #assign groups igraph::V(g)$group <- sex  #Check group values again print(igraph::V(g)$group) #[1] "Male"   "Male"   "Male"   "Male"   "Male"   "Female" "Female" "Female" "Female" "Female"  # I use visnetwork to visualise  vis_g <- visNetwork::toVisNetworkData(g, idToLabel = TRUE)   visNetwork::visNetwork(   nodes = vis_g$nodes,   edges = vis_g$edges   ) 
Answered on August 30, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.