NBK
NBK

Reputation: 905

r igraph - create tie between nodes based on their common connection and same type of tie to a third node

Nodes A and B are currently unconnected, and I want to connect them if they meet two conditions: 1) both are connected to the same third node; 2) the type of tie to that third node is the same. Say A and B are sons of the same father, then I want to identify them as siblings. How do I instruct r igraph to create this new tie? Take the following example.

edgelist <- read.table(text = "
A C
B C
C D")
graph <- graph.data.frame(edgelist, directed = F)
E(graph)[1]$weight <- 2
E(graph)[2]$weight <- 2
E(graph)[3]$weight <- 1

IGRAPH 0dd6cf1 DNW- 4 3 -- 
+ attr: name (v/c), weight (e/n)
+ edges from 0dd6cf1 (vertex names):
[1] A->C B->C C->D

In this example, A and B are connected to C, and both of their ties have weight 2. How do I connect A and B to each other but not to D? My actual network has thousands of nodes, so I need to automatise the process.

Upvotes: 0

Views: 503

Answers (1)

Esther
Esther

Reputation: 1115

There's probably a simpler way to do this, but I think this might give you what you want. I have expanded your example slightly to add multiple cases.

library(igraph)

options(stringsAsFactors = FALSE)

edgelist <- read.table(text = "
                       A C
                       B C
                       C D
                       D A
                       E C
                       D F
                       D G")

g <- graph.data.frame(edgelist, directed = F)

E(g)$weight <- c(2,2,1,1,2,2,2)

#plot graph, scaling the weights just to make them more obvious
plot(g, edge.width = E(g)$weight*3)

original network

#convert back to edgelist
el <- as.data.frame(get.edgelist(g))
el$weight <- E(g)$weight

ids <- unique(c(el$V1, el$V2))

#select sets of alters of all nodes that have edge weight equal to 2 
y <- lapply(ids, function(id) {

  x <- el[which(el$V1 == id | el$V2 == id),]
  x <- x[which(x$weight == 2),]
  alt_nodes <- setdiff(unique(c(x$V1, x$V2)), id)

})

#select sets that have 2 or more edges with weight 2
ly <- which(unlist(lapply(y, length))>= 2)

#add connections of weight 1 between all of these sets of nodes
res <- lapply(ly, function (i) {

  new_edge <- y[[i]]
  ne <- t(combn(new_edge,2))
  ne <- cbind(ne, rep(1, nrow(ne)))
  colnames(ne) <- names(el)
  el< <- rbind(el, ne)

})

#convert back to graph
g2  <-  graph.data.frame(el, directed  =  F)
E(g2)$weight <- el$weight

plot(g2, edge.width = as.numeric(E(g2)$weight)*3)

network with added edges

Upvotes: 1

Related Questions