Is there a certain R-gotcha that had you really surprised one day? I think we'd all gain from sharing these.
Here's mine: in list indexing, my.list[[1]] is not my.list[1]. Learned this in the early days of R.
Is there a certain R-gotcha that had you really surprised one day? I think we'd all gain from sharing these.
Here's mine: in list indexing, my.list[[1]] is not my.list[1]. Learned this in the early days of R.
which.min and which.max function opposite expectations when using comparison operator and can even give incorrect answers. So for example trying to figure out which element in a list of sorted numbers is the largest number that is less than a threshold. (i.e. in a sequence from 100 to 200 which is the largest number that is less than 110)
set.seed(420)
x = seq(100, 200)
which(x < 110)
> [1] 1 2 3 4 5 6 7 8 9 10
which.max(x < 110)
> [1] 1
which.min(x < 110)
> [1] 11
x[11]
> [1] 110
max(which(x < 110))
>[1] 10
x[10]
> [1] 109
The dirties gotcha that can be really hard to find! Cutting multi-line expressions like this one:
K <- hyperpar$intcept.sigma2
+ cov.NN.additive(x1$env, x2 = NULL, sigma2_int = hyperpar$env.sigma2_int, sigma2_slope = hyperpar$env.sigma2_slope)
+ hyperpar$env.sigma2 * K.cache$k.env
R will only evaluate the first line, and the other two will just go waste! And it will not say any warning, nothing! This is pretty nasty treachery on unsuspecting user. It must actually be written like this:
K <- hyperpar$intcept.sigma2 +
cov.NN.additive(x1$env, x2 = NULL, sigma2_int = hyperpar$env.sigma2_int, sigma2_slope = hyperpar$env.sigma2_slope) +
hyperpar$env.sigma2 * K.cache$k.env
which is not quite natural way of writing.
This one!
all(c(1,2,3,4) == NULL)
$[1] TRUE
I had this check in my code, I really need both tables to have the same column names:
stopifnot(all(names(x$x$env) == names(x$obsx$env)))
But the check passed (evaluated to TRUE) when x$x$env didn't even exist!
You can use options(warn = 2), which, according to the manual:
If warn is two or larger all warnings are turned into errors.
Indeed, the warnings are turned into errors, but, gotcha! The code still continues running after such errors!!!
source("script.R")
# ...
# Loading required package: bayesmeta
# Failed with error: ‘(converted from warning) there is no package called ‘bayesmeta’’
# computing posterior (co)variances ...
# (script continues running)
...
PS: but some other errors converted from warning do stop the script... so I don't know, I am confused. This one did stop the script:
Error in optimise(psiline, c(0, 2), adiff, a, as.matrix(K), y, d0, mn, :
(converted from warning) NA/Inf replaced by maximum positive value