[R] Odp: How to make t.test handle "NA" and "essentially constant values" ?

hadley wickham h.wickham at gmail.com
Tue Feb 12 23:43:21 CET 2008


> Speaking from personal experience, it can be quite a drag when one has set
> up and mostly-debugged a long computation only to have it stop with an
> error like "data are essentially constant" right near the end because of
> some condition for which the function author thought it better to stop with
> an error rather than return NA (or some other indication that there was no
> sensible answer) (didn't happen with t.test, but I've experienced it with a
> few other functions.)
>
> So, I don't think it's at all unreasonable for the OP to request a way to
> make t.test() return NA instead of stopping with an error.
>
> Looking at the code for t.test, it doesn't look like there's any argument
> to specify such behavior, so the options are to write one's own version of
> t.test, or use try() as other posters have suggested.  Here's an example
> using try():
>
>  > my.t.test.p.value <- function(...) {
> +    obj<-try(t.test(...), silent=TRUE)
> +    if (is(obj, "try-error")) return(NA) else return(obj$p.value)
> + }

I've written the following functions to make these tasks a little easier:

try_default <- function (expr, default = NA) {
  result <- default
  tryCatch(result <- expr, error = function(e) {})
  result
}

failwith <- function(default = NULL, f, ...) {
  function(...) try_default(f(...), default)
}

so my.t.test.p.value could be created as:

my.t.test.p.value <- function(...) failwith(NA, t.test(...))


Hadley


-- 
http://had.co.nz/



More information about the R-help mailing list