I am currently working on a project visualizing a network of think tank board members and their respective boards. The data I have is in the following format:
name edge
1 A 1
2 A 2
3 A 3
4 B 4
5 B 5
6 C 6
However, to make it compatible for igraphs graph_from_data_frame()
function, I would need the following format:
name from to
1 A 1 2
2 A 1 3
3 A 2 3
4 B 4 5
5 C 6 0
I have already tried
df1 <- setDT(df1)[, list(edge = toString(edge)), name]
df1 <- separate(df1, "edge", c("X", "Y", "Z"))
yielding
name X Y Z
1: A 1 2 3
2: B 4 5 <NA>
3: C 6 <NA> <NA>
However, I do not know how to get from this (or the initial format) to the required format to use graph_from_data_frame()
I hope you can help me. Thanks in advance
CodePudding user response:
You could use combn
by
each name with a small case handling.
by(dat, dat$name, \(x) {
e <- x$edge
if (length(e) == 1L) e <- c(e, 0L)
cbind(x$name[1L], t(combn(e, 2L)))
}) |>
do.call(what=rbind.data.frame) |>
setNames(c('name', 'from', 'to'))
# name from to
# A.1 A 1 2
# A.2 A 1 3
# A.3 A 2 3
# B B 4 5
# C C 6 0
Note: R >= 4.1 used.
Data:
dat <- structure(list(name = c("A", "A", "A", "B", "B", "C"), edge = 1:6), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))