#Made this function on 02 Nov 2018 to take a node list and convert it into an edge list. #Here, I am using the language of UCINTE where node list = ego, alter1, alter2, alterN. #You supply a node list and save as a data frame. #Note, you need to pad the rows with NA out to the longest row in the dataset. #The function will automatically omit NAs and convert the node list into ego alter pairs. #It starts with the first row, creates a n x 2 data set, then appends the next row below and so on. #The function also returns a list of all nodes and the number of times that they appear in the original data. NOTE, this includes ego & alters, it is not a measure of indegree. #Function also returns the number of dyads and number of nodes. node2edgelist<- function(myNodeList){ myRows<-dim(myNodeList)[1] myEdgeList<-data.frame() for(Q in 1:myRows){ N1<-as.character(rep(myNodeList[Q:Q,1:1], (sum(!is.na(myNodeList[Q,]))-1))) #get ego for as many times as there are alters N2<-myNodeList[Q,] [!is.na(myNodeList[Q,])] [-1] #get first row, subset by not NA, then remove col 1 (i.e., "ego") tempData<-data.frame(matrix(c(N1,N2), nrow=length(N2),ncol=2,byrow=FALSE)) myEdgeList<-rbind(myEdgeList,tempData) } numberDyads<-(sum(!is.na(myNodeList)))-myRows #sum of non NAs minus nrows (i.e., "egos") numberNodes<-length(table(as.matrix(myNodeList,ncol=1))) #vectorize. 1 col matrix is a vector. listNodes<-data.frame(table(as.matrix(myNodeList,ncol=1))) return(list(myEdgeList=myEdgeList, listNodes=listNodes, numberDyads=numberDyads, numberNodes=numberNodes)) } ### TEST DATA #### animals1<-data.frame(matrix( c("raccoon","whale", "dugong", NA, "otter", "raccoon", "whale", "chicken", "dugong", "otter", "blue crab", NA), nrow=3,ncol=4,byrow=TRUE)) animals2<-data.frame(matrix( c("dog", "cat", "fish", "bird","orangutan", NA, "monkey", "lamb", "orangutan", "zebu", "hog", "quagga", "doe", "gopher", "badger", "colt", NA, NA, "otter", "chinchilla", "turtle", NA, NA, NA, "lamb", "monkey", "turtle", NA, NA, NA), nrow=5, ncol=6, byrow=TRUE)) catNames<-data.frame(matrix( c("Muffin", "Mittens","Coco Chanel","Jasmine","Emma","Lucky", "Boots", "Phoebe", "Socks", "Izzy", "Coco Chanel", "Lilly", "Fiona", "Noodle", "Bella", "Sebastian", "Murphy", "Lilly", "Lilly", "Tigger", "Shakira", NA, NA, NA, "Muffin", "Peanut", "Beyonce", NA, NA, NA, "Boomer", "Lilly", "Phoebe", NA, NA, NA, "Lady Gaga", "Sammy", "Toby", NA, NA, NA, "Phoebe", "Socks", "Lady Gaga", NA, NA, NA), nrow=8, ncol=6, byrow=TRUE)) ######################################### #Let's do some tests #Run function node2edgelist(animals1) node2edgelist(animals2) node2edgelist(catNames) #call just a specific output testRun<-node2edgelist(animals1) testRun$myEdgeList testRun$numberNodes