Tuesday, October 2, 2012

Simulating Social Network Data

# Code updated: Sorry about that sometimes blogger seems to go crazy with the code thinking it is html or something.

# This simulation will generate a simulated data set with social network connections.

# For reference on how to us R to analyze social networks, check out: Mike Nowak and Sean Westwood. 2010. "Social Network Analysis Labs in R." Stanford University.

# First lets decide how many people we would like to simulate in our social network.

npeople = 50
# We will create an edgelist which defines all of the relationships between everybody in the network.

# First let's create a pure random network.

# First we will populate it by a list of all of the edges.

rnet <- data.frame(ego=rep(1:npeople,each=npeople), alter=rep(1:npeople,times=npeople), friendship=0)

# Right now we have all of the edges (npeople^2) and now we just need to populate it with connections.

# These connection will be random on our first pass at this.

# Because these connections are "friendship" connections we will assume that they go both directions.

# Let's define the density of connections:  Ie number of connections per potential connection.

conDen = .05

# This double loop should make it so that every connection is examined for a potential connection

for (i in 1:npeople) for (ii in (i+1):npeople) if ((rbinom(1,1,conDen)==1)&(i!=ii)) {
  rnet$friendship[(rnet$ego==i & rnet$alter==ii)] <- 1
  rnet$friendship[(rnet$ego==ii & rnet$alter==i)] <- 1


# We can see that as we had planned there is a specific number of connections.

# For graphing our connections we will use the package igraph

# Let's try generating our first graph:
plot(graph.data.frame(rnet[rnet$friendship==1,], directed=F), main="Purely Random Connections")

# I reran this code a number of times before I found a network that did not have any stray members who were unconnected.  However, a large portion of the time at least one member us unconnected with the larger network.

# In later posts I will enrich this simulation to allow for networks to be generated dynamically.  That is friends bridge friendships between friends.

No comments :

Post a Comment