Skip to content

Instantly share code, notes, and snippets.

@dnanto
Last active April 8, 2020 16:25
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 dnanto/86bb78d9e1a60098201cd88a655fa1f3 to your computer and use it in GitHub Desktop.
Save dnanto/86bb78d9e1a60098201cd88a655fa1f3 to your computer and use it in GitHub Desktop.
R function to read a DOT file into an igraph obj
library(tidyverse)
library(igraph)
parse_attr <- function(val)
{
tokens <-
str_split(val, '(,)(?=(?:[^"]|"[^"]*")*$)') %>%
lapply(str_split, '(=)(?=(?:[^"]|"[^"]*")*$)') %>%
unlist() %>%
str_trim() %>%
str_remove('^"') %>%
str_remove('"$')
setNames(tokens[c(F,T)], tokens[c(T,F)])
}
read_dot <- function(path)
{
lines <- read_lines(path) %>% str_trim()
edge <- if(startsWith(lines[1], "digraph")) ">" else "-"
e <-
str_match(lines, str_c("(\\d+) -", edge, " (\\d+)")) %>%
as.data.frame() %>%
filter(complete.cases(.)) %>%
select(-V1) %>%
setNames(c("from", "to"))
v <-
str_match(lines, "(\\d+)\\[(.+)\\]") %>%
as.data.frame() %>%
filter(complete.cases(.)) %>%
select(-V1) %>%
setNames(c("id", "attr")) %>%
bind_cols(map_df(lapply(.$attr, parse_attr), bind_rows))
list(v, e)
}
g <- read_dot("/path/to/dot/file.gv")
g <- graph_from_data_frame(g[[2]], vertices = g[[1]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment