Visualizing R Function Dependencies

Viewed 6672

There are a lot of resources for people who want to visualize package dependencies, but I'm interested specifically in visualizing functions within a package and their dependencies on one another. There are tools like miniCRAN for graphing package dependencies, but is there anything available to graph function dependencies within a package?

For example, suppose I only have two functions in my package.

func1 <- function(n) return(LETTERS[n])
func2 <- function(n) return(func1(n%%26+1))

Then I would just want a graph with two labeled nodes and an edge connecting them, depicting the dependency of func2 on func1.

I would think there are a lot of packages out there that have really hairy functional dependencies that such a utility could help in understanding/organizing/refactoring/etc.

Thanks.

3 Answers

For the sake of completeness, and as a shameless plug, I'm developing another package to address this: foodwebr. The DependenciesGraphs package does not appear to have been updated for several years and I find the output of mvbutils::foodweb() hard to parse. All three packages use the same dependency detection algorithm under the hood.

Using the original example:

e <- new.env()
e$func1 <- function(n) return(LETTERS[n])
e$func2 <- function(n) return(func1(n%%26+1))

fw <- foodwebr::foodweb(env = e)

fw
#> # A `foodweb`: 2 vertices and 1 edge 
#> digraph 'foodweb' {
#>   func1()
#>   func2() -> { func1() }
#> }

Calling plot() shows the graph (can't upload images as this is my first post):

plot(fw)

You can also use tidygraph::as_tbl_graph() to create a tidygraph object, which gives you more plotting and analysis options.

tidy_fw <- tidygraph::as_tbl_graph(fw)

tidy_fw
#> # A tbl_graph: 2 nodes and 1 edges
#> #
#> # A rooted tree
#> #
#> # Node Data: 2 x 1 (active)
#>   name 
#>   <chr>
#> 1 func1
#> 2 func2
#> #
#> # Edge Data: 1 x 2
#>    from    to
#>   <int> <int>
#> 1     2     1

The package is still in development but you can use devtools::install_github("lewinfox/foodwebr") to give it a go.

Related