library(tidyverse)
library(igraph)
df = tibble(
class = c("1","1","1","2","2","2","3","3","3"),
name = c("a","b","c","d","e","f","g","h","i")
)
names = df %>% select(name)
relations = df %>%
mutate(name2 = df$name)
for (i in unique(select(df,class))$class){
from = relations %>%
filter(class == i) %>%
select(name)
to = relations %>%
filter(class == i) %>%
select(name2)
# Form relationships between all students in each class
if (i == 1){edge_list = crossing(from, to)}
else {edge_list = bind_rows(edge_list, crossing(from, to))}
}
# Prevent self-loop edges and duplicate relationships
edge_list = edge_list %>% filter(name != name2)
edge_list = edge_list[!duplicated(t(apply(edge_list, 1, sort))), ]
plot(graph_from_data_frame(edge_list, directed = FALSE, vertices = names))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…