[R] suprising behaviour of tryCatch()
Bill Dunlap
w||||@mwdun|@p @end|ng |rom gm@||@com
Thu May 18 16:50:34 CEST 2023
> The only difference is the use of ’=’ or ‘<-‘ to assign the p value of
the fisher test to the vector. I stopped using ‘<-‘ eons ago so it took a
bit to figure out.
The '=' has a context-dependent meaning - in a function call it is used to
name arguments and outside of a function call it is used for assignments.
This has nothing to do with tryCatch in particular. E.g.,
> f <- function(x) x + 100
> f(y <- 10)
[1] 110
> y
[1] 10
> f(y = 20)
Error in f(y = 20) : unused argument (y = 20)
> y
[1] 10
I recommend starting to use <- for assignments again (or not doing
assignments inside of function calls).
-Bill
On Thu, May 18, 2023 at 7:38 AM Calboli Federico (LUKE) <
federico.calboli using luke.fi> wrote:
> Hello,
>
> I run a fisher.test() in a loop, with the issue that some of the data will
> not be useable. To protect the loop I used tryCatch but:
>
> sexsnp = rep(NA, 1750)
> for(i in 1:1750){tryCatch(sexsnp[i] = fisher.test(table(data[,3], data[,i
> + 38]))$p, error = function(e) print(NA))}
> Error: unexpected '=' in "for(i in 1:1750){tryCatch(sexsnp[i] ="
>
> But this works:
>
> for(i in 1:1750){tryCatch(sexsnp[i] <- fisher.test(table(data[,3], data[,i
> + 38]))$p, error = function(e) print(NA))}
> [1] NA
> [1] NA
> [1] NA
>
> The only difference is the use of ’=’ or ‘<-‘ to assign the p value of the
> fisher test to the vector. I stopped using ‘<-‘ eons ago so it took a bit
> to figure out.
>
> Tested on R 4.1.2 on ContOS 8 , and on R 4.3.0 on a M1 mac with the same
> result. I’d be obliged if someone can explain why tryCatch assigns items
> with ‘<-‘ and not ‘=’.
>
> Cheers
>
> F
>
> Federico Calboli
> Tutkija
> Genomiikka ja jalostus
> Luonnonvarakeskus
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list