title: How to use saveRDS(..., refhook = ) parameter?
body: <p>I have a complicated list object, the output of a modelling function (asreml). The object contains all sorts of data types, including functions and formulas, which have environments attached. I don't want to save the environments to RDS, because they are quite big and I save a lot of models. </p>
  
  <p>I came across the parameter <code>refhook=</code> in the <code>serialize</code> and <code>saveRDS</code> functions. The documentation says:</p>
  
  <blockquote>
    <p>The refhook functions can be used to customize handling of non-system reference objects (all external pointers and weak references, and all environments other than namespace and package environments and .GlobalEnv). The hook function for serialize should return a character vector for references it wants to handle; otherwise it should return NULL.</p>
  </blockquote>
  
  <p>Given this example model</p>
  
  <pre><code>e &lt;- new.env()
  e$a = rnorm(10)
  l &lt;- list(a = e, b = 42)
  </code></pre>
  
  <p>The refhook function indeed show some effect. The output gets smaller when I define a function which returns a character, indicating that the environment does not get saved:</p>
  
  <pre><code>length(serialize(l, connection = NULL))
  [1] 338
  
  s &lt;- serialize(l, 
    connection = NULL, 
    refhook = function(x) "")
  length(s)
  [1] 109
  </code></pre>
  
  <p>However, I cannot read in the resulting object:</p>
  
  <pre><code>unserialize(s)
  
  Error in unserialize(s) : 
    no restore method available
  </code></pre>
  
  <p>I also tried a raw vector output, suspecting that maybe refhook is expected to provide an alternative serialized output, but that won't work:</p>
  
  <pre><code>s2 &lt;- serialize(l,
    connection = NULL, 
    refhook = function(x) 
      serialize("env", connection = NULL)))
  
  Error in serialize(l, con = NULL, refhook = function(x) serialize("env",  : 
    assertion 'TYPEOF(t) == STRSXP &amp;&amp; LENGTH(t) &gt; 0' failed: file 'serialize.c', line 982
  </code></pre>
  
  <p>How do I use <code>refhook=</code>? What character output is expected from this function?</p>