0

I see that comparing two values of type double should be done using e.g. all.equal or by pre-specifying a tolerance level, as discussed here.

But how would you solve this for two vectors of type double: u %in% v?

My solution so far is to use a double for-loop:

m <- vector("integer")
for (i in seq_along(u)) {
  for (j in seq_along(v)) {
    if (isTRUE(all.equal(u[[i]], v[[j]])))
      m <- c(m, i)
  }
}

Is there a better way (in terms of readability), or a more preferred way?

harisf
  • 149
  • 1
  • 1
  • 10
  • What is your code supposed to do, i.e. what is the intention of your vector m? – Erin Sprünken Mar 29 '20 at 16:58
  • To give the same result as `u %in% v`, namely the indices of `u` that match with values of `v`. Sorry for not being clear. – harisf Mar 29 '20 at 17:12
  • I don't see the problem there, %in% works for me. I have tested two vectors with random numbers (u = rnorm(10), v = u * sample(c(-1,1), 10, replace = T)) and u %in% v gave me the respective results. – Erin Sprünken Mar 29 '20 at 17:48
  • You're right! Note this, however: `(u = rnorm(10), v = u * sample(c(-1,1), 10, replace = T), v = as.numeric(as.character(v)))`. So it seems that converting from strings to numbers is what's really giving unexpected behavior in `u %in% v`. (In my case, the data in `u` consists of numbers originally entered as strings). – harisf Mar 29 '20 at 19:11
  • 1
    I see. But if I replicate that and use the round() function and take up to 14 decimals, I still get correct results (I used round(x, 14) on both u and v). So maybe there is a conversion problem somewhere after 15 decimals or so. – Erin Sprünken Mar 29 '20 at 20:23
  • 1
    Great! Thanks for helping me debug this. – harisf Mar 30 '20 at 10:00

0 Answers0