[R] tryCatch question
Henrik Bengtsson
hb at stat.berkeley.edu
Fri Sep 12 21:28:16 CEST 2008
On Fri, Sep 12, 2008 at 6:02 AM, Antje <niederlein-rstat at yahoo.de> wrote:
> Hi there,
>
> I have a nested call of lapply in which I do a tryCatch statement like this
>
> lapply(1:length(p_names), function(w_idx) {
> r <- as.numeric(pos_r[[w_idx]][1])
> c <- as.numeric(pos_c[[w_idx]][1])
> pos <- c(r,c)
> lapply(1:length(p_names[[w_idx]]), function(p_idx, pos) {
> parameter <- p_names[[w_idx]][[p_idx]]
> value <- p_vals[[w_idx]][[p_idx]]
>
> tryCatch({ as.numeric(value) }, warning = function(ex) {
> value})
> oad$resultValues[[parameter]][pos[1],pos[2]] <<- value
> NULL
> }, pos)
> })
>
> (sorry, that I don't have a simple test code here...)
> the tryCatch shall convert a value in a number if this makes sense (so "3.3"
> should be converted, but not "hello"; all values are strings)
>
> if I simply execute something like this:
>
> value <- "3.3"
> tryCatch({ as.numeric(value) }, warning = function(ex) { value})
>
> it works pretty nice. but within the lapply construct I always end up with
> strings.
> Does anybody have an idea why? (I can try to create a simple testcode for
> this but maybe there is already someone who knows what's wrong?
***Anything*** you catch in a tryCatch() will ***interrupt*** the main
expression from being evaluated.
Example:
> x <- c("3.3", "2.1");
> tryCatch({ y <- as.numeric(x) }, warning = function(ex) { str(ex); })
> y;
[1] 3.3 2.1
There was no warning caught, so the main expression was completely
evaluated and 'y' got assigned. Now consider this:
> x <- c("3.3", "a");
> tryCatch({ z <- as.numeric(x) }, warning = function(ex) { str(ex); })
List of 2
$ message: chr "NAs introduced by coercion"
$ call : language doTryCatch(return(expr), name, parentenv, handler)
- attr(*, "class")= chr [1:3] "simpleWarning" "warning" "condition"
> z;
Error: object "z" not found
See how the warning is caught and tryCatch() is finished immediately.
So, if the string contains a numeric value you wish to convert it,
otherwise keep it as is, correct? If you don't have NAs, Infs etc in
your strings, then you can easily to as follows:
> value <- "3.3";
> value2 <- as.double(value);
> # If not a valid number, keep original value
> if (is.na(value2)) value2 <- value;
> value2
[1] 3.3
> value <- "hello";
> value2 <- as.double(value);
Warning message:
NAs introduced by coercion
> if (is.na(value2)) value2 <- value;
> value2
[1] "hello"
If you want "NA" to become as.double(NA) etc, then you have to add
identical(value, "NA") etc.
/Henrik
>
> Ciao,
> Antje
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list