Skip to content

Instantly share code, notes, and snippets.

@fkeck
Created March 23, 2018 19:17
Show Gist options
  • Select an option

  • Save fkeck/2feac0d7292ea1eceb2ee967ba6acfa6 to your computer and use it in GitHub Desktop.

Select an option

Save fkeck/2feac0d7292ea1eceb2ee967ba6acfa6 to your computer and use it in GitHub Desktop.
Load jean.dat in R
# Read and parse "jean.dat" from the Stanford GraphBase (C) 1993 Stanford University
library(tidyverse)
library(stringr)
library(igraph)
library(tidygraph)
jean <- readLines("http://ftp.cs.stanford.edu/pub/sgb/jean.dat")
jean <- jean[!str_detect(jean, "^\\*")]
jean_sep <- which(jean == "")
jean_nodes <- jean[1:(jean_sep - 1)]
jean_edges <- jean[(jean_sep + 1):length(jean)]
jean_nodes <-
jean_nodes %>%
str_replace_all("(\t)+$", "") %>%
str_replace_all("(\t)+", "\t") %>%
str_replace_all("(?<=^[A-Z]{2}) ", "\t") %>%
str_replace_all(", ", "\t") %>%
str_c(collapse = "\n") %>%
read_tsv(col_names = c("Node_ID", "Node_name", "Node_desc"), col_types = "ccc")
comb_edge_list <- function(x){
x <- str_split(x, ",")
x <- unlist(x)
if(length(x) == 1) x <- c(x, x)
x <- combn(x, m = 2)
x <- t(x)
}
jean_edges_chap <- str_extract(jean_edges, "^\\d+\\.\\d+\\.\\d+")
jean_edges <-
jean_edges %>%
str_extract("(?<=:).*") %>%
str_replace_all(pattern = " ", replacement = "") %>%
str_replace_all(pattern = ";$|,$", replacement = "") %>%
str_split(";") %>%
map(str_split, pattern = ",") %>%
modify_depth(2, comb_edge_list) %>%
map(., function(x) do.call("rbind", x)) %>%
map2(., jean_edges_chap, cbind) %>%
map2(., seq_along(jean_edges_chap), cbind) %>%
do.call("rbind", .) %>%
as_tibble() %>%
transmute(Node_1 = V1, Node_2 = V2,
Chapter = V3, Chapter_n = as.integer(V4))
jean_graph <-
jean_edges %>%
select(Node_1, Node_2) %>%
filter(!is.na(Node_1)) %>%
as.matrix() %>%
graph.edgelist(directed = FALSE) %>%
as_tbl_graph()
rm(jean, jean_edges_chap, jean_sep, comb_edge_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment