From peter.langfelder at gmail.com  Tue Aug 20 22:36:24 2013
From: peter.langfelder at gmail.com (Peter Langfelder)
Date: Tue, 20 Aug 2013 13:36:24 -0700
Subject: [Rd] Extending suggestion for stopifnot
In-Reply-To: <CAPr7RtX3b5XBzgn1XT3nPcvX71G=W1CpK=tK1T3zz4zWW=pQNQ@mail.gmail.com>
References: <CAPr7RtX3b5XBzgn1XT3nPcvX71G=W1CpK=tK1T3zz4zWW=pQNQ@mail.gmail.com>
Message-ID: <CA+hbrhVcih5+u1hV5c2c_+HC6UJ6BzpdwmP4VWuuU=gdNmkz1Q@mail.gmail.com>

On Tue, Aug 20, 2013 at 11:41 AM, ivo welch <ivo.welch at anderson.ucla.edu> wrote:
> I am using a variant of stopifnot a lot.  can I suggest that base R
> extends its functionality?  I know how to do this for myself.  this is
> a suggestion for beginners and students.  I don't think it would break
> anything.
>
> first, I think it would be more useful if it had an optional character
> string, so users could write
>
>   stopifnot( is.matrix(m), "m is not a matrix" )
>
> this would mean that stopifnot would have to detect whether the last
> argument is a string.  (I think stopifnot should have had only one
> condition, and one should have used all() to test multiple conditions,
> but this is a bridge that was already crossed.)  upon failure,
> stopifnot should print the character string.  that's it.
>
>
> A second enhancement would be a "smart string", which knows that
> everything inside {{...}} should be evaluated.
>
>   stopifnot( is.matrix(m), "m is not a matrix, but a {{class(m)}}" )

I think using a function (in this case paste) is cleaner:

paste("m is not a matrix, but a", class(m))

It avoids adding a new convention ("evaluate everything between {{
}}") and has additional arguments.

>
>
> my own programming variant looks even nicer,
>
>    is.matrix(m) %or% "m is not a matrix but a {{class(m)}}"

In R you can write it as

is.matrix(m) || stop("m is not a matrix but a ", class(m))

Examples:

m = 1
> is.matrix(m) || stop("m is not a matrix but a ", class(m))
Error: m is not a matrix but a numeric

> m = matrix(0,2,2)
> is.matrix(m) || stop("m is not a matrix but a ", class(m))
[1] TRUE

But the construct

if (!is.matrix(m)) stop("m is not a matrix but a ", class(m))

is more readable for people not used to Pearl.



[Rd] Extending suggestion for stopifnot
Peter Langfelder