rsnabnlearn

R masking conflict: packages bnlearn and sna


I have problems to parallely use R packages bnlearn and sna. The following example is straightforward:

library(bnlearn)
data("asia")

# build network
a <- hc(asia)

# output
a

The output is as expected:

  Bayesian network learned via Score-based methods

  model:
   [A][S][T][L|S][B|S][E|T:L][X|E][D|B:E] 
  nodes:                                 8 
  arcs:                                  7 
    undirected arcs:                     0 
    directed arcs:                       7 
  average markov blanket size:           2.25 
  average neighbourhood size:            1.75 
  average branching factor:              0.88 

  learning algorithm:                    Hill-Climbing 
  score:                                 BIC (disc.) 
  penalization coefficient:              4.258597 
  tests used in the learning procedure:  77 
  optimized:                             TRUE 

Once I load the sna package, I receive something completely different:

library(sna)

#output
a

I get:

Biased Net Model

Parameters:

Error in matrix(c(x$d, x$pi, x$sigma, x$rho), ncol = 1) : 
  'data' must be of a vector type, was 'NULL'

As I don't really call any functions (just want to get the output of a), I don't think that using the :: operator can help.

I wonder if the problem is masking of an internal function that I can't really influence. Any help would be great!


Solution

  • This is somewhat similar to other q & a's except in this case there is an implicit call to print, rather than an explicit function call. It is this print function that is getting masked.

    To print a, you can either type a in the terminal, or be explicit and type print(a). To get the nice print layout of the bn object, the author has written a print method, and this is what is dispatched when typing either a or print(a). (To see it without this specific printing you can use print.default(a)). After noting that the class(a) == "bn", you can look for the print method, by using methods("print") or typing bnlearn:::print and then <tab> to see available functions: this leads to a (non-exported) function bnlearn:::print.bn.

    So long story short, the sna package also has a print.bn method, for objects of class "bn" (biased net), and it is this function that masks the one from bnlearn.

    So if you load sna after bnlearn, you can still get the nice printing by either explicitly using bnlearn:::print.bn(a), or redefine the print method print.bn <- bnlearn:::print.bn, and it should print as expected.