In_class_Exercise 3

Author

Hao Liu

Published

May 17, 2025

Modified

June 17, 2025

Loading necessary packages:

# Load libraries
pacman::p_load(tidyverse,jsonlite,
               SmartEDA,tidygraph,
               ggraph)

Use fromJSON to import data:

kg <- fromJSON("MC1_graph.json")

Inspect structure:

str(kg, max.level=1)
List of 5
 $ directed  : logi TRUE
 $ multigraph: logi TRUE
 $ graph     :List of 2
 $ nodes     :'data.frame': 17412 obs. of  10 variables:
 $ links     :'data.frame': 37857 obs. of  4 variables:

Extract and Inspect:

nodes_tbl <- as_tibble(kg$nodes)
edges_tbl <- as_tibble(kg$links)

Initial EDA:

ggplot(data = edges_tbl,
       aes(y = `Edge Type`)) +
  geom_bar()

Creating Knowledge Graph

step 1: mapping from node id to row index

id_map <- tibble(id = nodes_tbl$id,
                 index = seq_len(
                   nrow(nodes_tbl)))

step 2: Map source and target ids to row indices

edges_tbl <- edges_tbl %>%
  left_join(id_map, by = c("source" = "id")) %>%
  rename(from = index) %>%
  left_join(id_map, by = c("target" = "id")) %>%
  rename(to = index)

step 3: Creating the Graph

graph <- tbl_graph(nodes = nodes_tbl,
                   edges = edges_tbl,
                   directed = kg$directed)

step 4: Visualising the Knowledge Graph

set.seed(1234)
ggraph(graph, layout = "fr") +
  geom_edge_link(alpha = 0.3, colour = "gray") +
  geom_node_point(aes(color = `Node Type`), size = 4) +
  geom_node_text(aes(label = name),
                 repel = TRUE,      # R’s logical constant
                 size = 2.5) +
  theme_void()

Cleaning up

Filter Edges to only “MemberOf”

graph_memberof <- graph %>%
  activate(edges) %>%
  filter(`Edge Type` == "MemberOf")

Extract only connected nodes (i.e., used in these edges)

used_node_indices <- graph_memberof %>%
  activate(edges) %>%
  as_tibble() %>%
  select(from, to) %>%
  unlist() %>%
  unique

Keep only those nodes

graph_memberof <- graph_memberof %>%
  activate(nodes) %>%
  mutate(row_id = row_number()) %>%
  filter(row_id %in% used_node_indices) %>%
  select(-row_id) #optional cleanup

Plot the subgraph

ggraph(graph_memberof,
       layout = "fr") + 
  geom_edge_link(alpha = 0.5,
                 colour = "gray") +
  geom_node_point(aes(color = `Node Type`),
                  size = 1) + 
  geom_node_text(aes(label = name),
                 repel = TRUE,
                 size = 2.5) +
  theme_void()