0
votes

I am working on a network graph in R, and need to do a simple data manipulation. I have a dataframe of nodes that looks as such:

dput(mynodes)
structure(list(id = c("s1", "s2", "s3", "s4", "s5", "s6", "s7", 
"s8"), name = c("Jim", "Mike", "Bob", "Joe", "John", "Rob", "Kyle", 
"Chad")), .Names = c("id", "name"), row.names = c(NA, 
-8L), class = "data.frame")

mynodes
  id name
1 s1  Jim
2 s2 Mike
3 s3  Bob
4 s4  Joe
5 s5 John
6 s6  Rob
7 s7 Kyle
8 s8 Chad

And I would like to initialize a dataframe for all possible edge combinations between these nodes. My desired output then is a dataframe that looks like this:

   from   to
 1   s1   s2
 2   s1   s3 
 3   s1   s4 
 4   s1   s5 
 5   s1   s6
 6   s1   s7
 7   s1   s8 
 8   s2   s1
 9   s2   s3
10   s2   s4
... ... ... 

and so on, all the way for each unique pairing of ids from mynodes. Is there an easy way to do this, possibly using the igraph package (since I'm going to create a net using the graph_from_data_frame function in igraph).

Any help is appreciated, thanks!!

2

2 Answers

1
votes

If you want to save few lines

df <- structure(list(id = c("s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"), name = c("Jim", "Mike", "Bob", "Joe", "John", "Rob", "Kyle", "Chad")), .Names = c("id", "name"), row.names = c(NA, -8L), class = "data.frame")


result <- as.data.frame(t(combn(df$id,2)))
colnames(result) <- c('from','to')
0
votes

I'll answer my own question quick here, since I got it myself:

data.frame(from = rep(mynodes $id, each = length(mynodes $id)),
           to = rep(mynodes $id, times = length(mynodes $id)), 
           stringsAsFactors = FALSE) %>%
filter(to != from)