Last active
April 8, 2020 16:25
-
-
Save dnanto/86bb78d9e1a60098201cd88a655fa1f3 to your computer and use it in GitHub Desktop.
R function to read a DOT file into an igraph obj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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