Add Health Network (supplement)

Download R source file
            
              # Saves one of the faux Add Health networks, and adds a fake attitude value
# Author: Jake Fisher

# Set up workspace
rm(list = ls())
setwd("C:/Users/fishe/Box Sync/Home Folder jcf26/SNH2017/Instructor dropbox")
library(tidyverse)
library(statnet)

# Let's work from one of the faux Add Health networks
faux <- read.csv("ahs_wpvar.csv")

# Subset out network 1 and convert to an edgelist
el <- faux %>%
  filter(commcnt == 1) %>%
  dplyr::select(ego_nid, dplyr::contains("fnid")) %>%
  gather(key = "nomination", value = "alter", -ego_nid) %>%
  mutate(alter = ifelse(alter == 99999, NA, alter)) %>%
  select(-nomination) 

# Save a list of the unique people
ah.people <- with(el, unique(c(ego_nid, alter)))  # this would be all the people, including those out of school
# ah.people <- unique(dat$ego_nid)  # this is only people who took the survey

# Drop missing cases
el %<>% filter(!is.na(alter))  # separate step, so we don't drop people who
                               # don't list anyone (i.e. have all NA's for 
                               # friends)
ah.people <- subset(ah.people, !is.na(ah.people))

# Now create an empty network
add.health <- network.initialize(n = length(ah.people))

# statnet adds edges by index values, not by names of variables.  So, to make
# this work, we have to create an index value of 1, 2, ..., N, where N is the
# number of people in the network
el %<>%
  mutate(ego.idx = match(ego_nid, ah.people), 
         alter.idx = match(alter, ah.people))


# Add the edges from the edgelist
add.edges(add.health, el$ego.idx, el$alter.idx)

# Add a simulated attitude variable
set.seed(919)
faux.attitude <- sample(1:5, size = length(ah.people), replace = T)

# Attach fake attitude to the network
add.health %v% "faux.attitude" <- faux.attitude

save(add.health, file = "faux_add_health_with_faux_attitude.Rdata")