[R] suprising behaviour of tryCatch()
Berwin A Turlach
berw|n@tur|@ch @end|ng |rom gm@||@com
Thu May 18 17:44:31 CEST 2023
G'day Greg,
On Thu, 18 May 2023 08:57:55 -0600
Greg Snow <538280 using gmail.com> wrote:
[...]
> `fun(x <- expr)` Assigns the value of `expr` to the variable `x` in
> the frame/environment that `fun` is called from.
Only if the argument 'x' is evaluated during the function call AFAIK.
If it is not, due to lazy evaluation rules, then no assignment takes
place.
> When you run the code with `<-` it, then the ith element of the global
> variable `sexsnp` is assigned the p-value. When you run the version
> with `=` then R tries to find an argument to `tryCatch` that matches
> (possibly partially) `sexsnp[i]` and gives the error because it does
> not find a match (not sure why it is not handled by `...`, but
> tryCatch may be parsed special, or non-legal argument names on the RHS
> of `-` may be checked).
After exact matching on names comes partial matching on names and then
positional matching. If after these three rounds there are still
actual arguments left over, they are assigned to "..." (if it exist as
formal argument).
So under the usual rules of how actual arguments
are passed to formal arguments in Federico's call the argument
"sexsnp[i] = fisher.test(table(data[,3], data[,i + 38]))$p" should be
assigned to the formal argument "expr" of tryCatch() and "error =
function(e) print(NA))" should be absorbed by "...".
But it seems, as "=" has a different meaning in function call, the
expression passed to the "expr" formal argument is not allowed to
contain a "=". Not sure why. :-)
I guess that the intended use is actually:
R> for(i in 1:1750){sexsnp[i] = tryCatch(fisher.test(table(data[,3], data[,i + 38]))$p, error = function(e) print(NA))}
I.e. tryCatch() returns the result of the evaluated expression (if
successful, otherwise the result of an error handler) and that result
can be assigned. It is not expected the that expression contains an
assignment operation. But I am just guessing. :)
Cheers,
Berwin
More information about the R-help
mailing list