testwhat icon indicating copy to clipboard operation
testwhat copied to clipboard

Document how to check igraphs

Open richierocks opened this issue 6 years ago • 4 comments

igraphs are annoying to check, since they contain weakrefs (pointers to memory addresses of external objects), which are unique each time they are created. That means that check_equal() doesn't work.

Typically, the exercise will ask the student to create a graph from a data frame. This code is taken from ?graph_from_data_frame.

library(igraph)
actors <- data.frame(
  name=c("Alice", "Bob", "Cecil", "David", "Esmeralda"),
  age=c(48,33,45,34,21),
  gender=c("F","M","F","M","F")
)
relations <- data.frame(
  from=c("Bob", "Cecil", "Cecil", "David", "David", "Esmeralda"),
  to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"),
  same.dept=c(FALSE,FALSE,TRUE,FALSE,FALSE,TRUE),
  friendship=c(4,5,5,2,1,1), 
  advice=c(4,5,5,4,2,3)
)
g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors)

After some experimentation, this is the best set of SCTs I can come up with.

ex() %>% {
  check_object(., "g")
  check_expr(., 'is_igraph(g)') %>% 
    check_result() %>% 
    check_equal(incorrect_msg = 'Did you use `graph_from_data_frame()` to make `g` into an igraph?')
  check_expr(., 'as_data_frame(g)') %>% 
    check_result() %>% 
    check_equal(incorrect_msg = 'Did you use `relations` for the graph edges?')
  check_expr(., 'as_data_frame(g, "vertices")') %>% 
    check_result() %>% 
    check_equal(incorrect_msg = 'Did you use `actors` for the graph vertices?')
  check_expr(., 'is_directed(g)') %>% 
    check_result() %>% 
    check_equal(incorrect_msg = 'Did you set `directed` to `TRUE`?')
}

Long term, it would be nice to have check_igraph() that wraps this functionality. In the short term, having an example like this in the docs would be helpful.

richierocks avatar Nov 01 '18 19:11 richierocks

The vertices is optional; if it isn't present in the code then

check_expr(., 'as_data_frame(g, "vertices")') %>% 
    check_result() %>% 
    check_equal(incorrect_msg = 'Did you use `actors` for the graph vertices?')

probably isn't needed.


If directed is FALSE for the graph, then the last incorrect_msg needed to be changed.

richierocks avatar Nov 01 '18 19:11 richierocks

Thanks for the extensive code example! Would it make sense to add check_igraph() as functionality in https://github.com/datacamp/testwhat.ext?

hermansje avatar Nov 02 '18 11:11 hermansje

Yes, I think check_igraph() is niche enough that it makes more sense in testwhat.ext.

richierocks avatar Nov 02 '18 16:11 richierocks

Oh, one thing to watch out for: igraph and tibble both have an as_data_frame() function; you need to make sure the igraph one is called.

richierocks avatar Nov 02 '18 19:11 richierocks