I was trying to match a numeric to a vector, as following:
t <- seq(-4,4,length=81)
tifl.e <--1.5
tifc.e <--0.5
tifr.e <-0.5
tifl.m <--1.6
tifc.m <--0.4
tifr.m <-0.8
match( c(tifl.e, tifc.e, tifr.e), t)
[1] 26 36 46
match( c(tifl.m, tifc.m, tifr.m), t)
[1] NA NA NA
I also tried the code, but it gave the same results.
tifl.cut <-c(-1.5,-1.6)
tifc.cut <-c(-0.5,-0.4)
tifr.cut <-c(0.5,0.8)
match( c(tifl.cut[1], tifc.cut[1], tifr.cut[1]), t)
[1] 26 36 46
match( c(tifl.cut[2], tifc.cut[2], tifr.cut[2]), t)
[1] NA NA NA
Meanwhile, I tried similar syntax by using %in%, which produced the exact same results.
So what is the problem in the syntax? How should I fix it?
Thanks for your inputs.
The right way to deal with floating point errors is to use all.equal. Here is a custom function for applying match to numerics and accounting for the possibility of floating point errors:
match.numeric <- function(x, table) {
are.equal <- function(x, y) isTRUE(all.equal(x, y))
match.one <- function(x, table)
match(TRUE, vapply(table, are.equal, logical(1L), x = x))
vapply(x, match.one, integer(1L), table)
}
match.numeric(c(tifl.e, tifc.e, tifr.e), t)
# [1] 26 36 46
match.numeric(c(tifl.m, tifc.m, tifr.m), t)
# [1] 25 37 49
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With