In an earlier post, we learned a command for one type of network homophily in R: the proportion of ties in a social network connecting two actors matching on a given characteristic. Today, we’ll build a command for calculating a second conception of network homophily. Specifically, this is the average proportion of characteristic matching within ego-networks, or the neighborhoods of each individual node.

First, let’s load igraph as we always do for these commands, and install it first if you need it:

1 2 |
# install.packages("igraph") library(igraph) |

Next, we’ll build the function for the ego-network homophily score, again commenting to describe each step in the function:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ego_homophily<-function(graph,vertex.attr){ #Get an empty vector of node-egonet homophily scores# homo<-as.vector(rep(NA,vcount(graph))) #For every node t in the network, we repeat the following:# for(t in 1:vcount(graph)){ #Only get homophily of ego-net if the node has neighbors, otherwise stays NA# if(degree(graph,V(graph)[t])>0){ #Collect the neighbors of the node in question# alters<-ego(graph,1,nodes=V(graph)[t],mode="out") #Collect the node's value on the specified attribute# ec<-get.vertex.attribute(graph,vertex.attr,V(graph)[t]) #Get proportion of neighbors with matching attribute value, assign to spot in vector# homo[t]<-sum(get.vertex.attribute(graph,vertex.attr,alters[[1]])==ec)/length(alters[[1]]) } } return(homo) } |