Skip to content

Instantly share code, notes, and snippets.

@charliejhadley
Created February 11, 2024 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charliejhadley/b83a4978fe5048aaeb13c934bf9995e1 to your computer and use it in GitHub Desktop.
Save charliejhadley/b83a4978fe5048aaeb13c934bf9995e1 to your computer and use it in GitHub Desktop.
starwars-graph.R
library(tidyverse)
library(ggraph)
library(tidygraph)
nodes_characters <- starwars %>%
mutate(character_id = row_number(), .before = 0) %>%
mutate(across(where(is.list), ~lengths(.x), .names = "n_{.col}"))
edges_reoccuring_co_stars <- nodes_characters %>%
filter(n_films > 1) %>%
select(character_id, films) %>%
unnest(films) %>%
left_join(.,
.,
by = "films",
relationship = "many-to-many") %>%
rename(from = character_id.x,
to = character_id.y) %>%
distinct() %>%
filter(from != to)
vec_reoccuring_costar_ids <- unique(c(edges_reoccuring_co_stars$from, edges_reoccuring_co_stars$to))
edges_flew_together <- nodes_characters %>%
filter(character_id %in% vec_reoccuring_costar_ids) %>%
select(character_id, starships) %>%
unnest(starships) %>%
left_join(.,
.,
by = "starships",
relationship = "many-to-many") %>%
rename(from = character_id.x,
to = character_id.y) %>%
distinct() %>%
filter(from != to)
tbl_graph(nodes_characters,
edges_flew_together) %>%
morph(to_components) %>%
mutate(graph_size = graph_size()) %>%
unmorph() %>%
filter(graph_size > 0) %>%
ggraph() +
geom_node_point() +
geom_edge_link() +
geom_node_label(aes(label = name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment