Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you're writing your own package, it might make sense to make use of R's condition system by throwing (and catching) particular types of errors or warnings. So</p> <pre><code>myFun &lt;- function(x) { if (any(is.na(x))) { w &lt;- simpleWarning("'x' contains NA values") class(w) &lt;- c("HasNA", class(w)) warning(w) } if (any(x &lt; 0)) warning("'x' contains values less than 0") x } </code></pre> <p>and then in your test, e.g., with <code>library(RUnit)</code>, use <code>tryCatch</code> and pick off just the conditions that you're interested in testing, i.e., warnings with class <code>HasNA</code>:</p> <pre><code>test_myFun_NAwarning &lt;- function() { warnOccurred &lt;- FALSE tryCatch(myFun(1:5), HasNA = function(w) warnOcccurred &lt;&lt;- TRUE) checkTrue(!warnOccurred) tryCatch(myFun(-(1:5)), HasNA = function(w) warnOcccurred &lt;&lt;- TRUE) checkTrue(!warnOccurred) tryCatch(myFun(c(1:5, NA)), HasNA = function(w) warnOccurred &lt;&lt;- TRUE) checkTrue(warnOccurred) } </code></pre> <p>leading to</p> <pre><code>&gt; test_myFun_NAwarning() [1] TRUE Warning message: In myFun(-(1:5)) : 'x' contains values less than 0 </code></pre> <p>which shows that tryCatch is catching just the particular warning you're interested in, and doing so in a way that does not rely on matching the text of the string. Maybe you'd have a helper function <code>.warn</code> to make all warnings for your package. See <code>?withCallingHandlers</code> for additional detail; <code>withCallingHandlers</code> and <code>muffleRestart</code> are how one might cope with continuing evaluation after a warning occurred, rather than stopping the way <code>tryCatch</code> does.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload