0

I have a numeric vector of 254 elements called smoothed_auto:

smoothed_auto
  [1] 0.4167147 0.4168202 0.4169259 0.4170314 0.4171361 0.4172395 0.4173410 0.4174401 0.4175435 0.4176561 0.4177743
 [12] 0.4178945 0.4180133 0.4181271 0.4182322 0.4183252 0.4184301 0.4185647 0.4187166 0.4188734 0.4190225 0.4191516
 [23] 0.4192480 0.4192995 0.4193022 0.4192707 0.4192201 0.4191651 0.4191207 0.4191017 0.4191231 0.4191997 0.4192655

(...)

And I am trying to find the indices of specific elements with the which() and match() functions:

which(smoothed_auto == 0.4167147)
#integer(0)

match(c(0.4167147), smoothed_auto)
#[1] NA

I have tried this with multiple elements and always get the same result. Any help?

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66

2 Answers2

0

This is R FAQ 7.31 and a duplicate of Why are these numbers not equal?.

A way of solving it is with a function I posted here.

are.equal <- function(x, y, tol = .Machine$double.eps^0.5) abs(x - y) < tol

which(are.equal(smoothed_auto, 0.4167147))
#[1] 1

Data

smoothed_auto <- scan(text = "
0.4167147 0.4168202 0.4169259 0.4170314 0.4171361 0.4172395 0.4173410 0.4174401 0.4175435 0.4176561 0.4177743
0.4178945 0.4180133 0.4181271 0.4182322 0.4183252 0.4184301 0.4185647 0.4187166 0.4188734 0.4190225 0.4191516
0.4192480 0.4192995 0.4193022 0.4192707 0.4192201 0.4191651 0.4191207 0.4191017 0.4191231 0.4191997 0.4192655
")
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thank you so much. Apparently, the numbers were rounded in the original vector (smoothed_auto was the output of a function, not a vector I created myself). That seems to be the source of the problem. Using the values from dput(), it works. – Clara Cavalcanti Feb 28 '21 at 14:11
0

Remove the c in match(c(0.4167147), smoothed_auto)

smoothed_auto <- as.vector(c(0.4167147, 0.4168202, 0.4169259, 0.4170314, 0.4171361, 0.4172395, 
  0.4173410, 0.4174401, 0.4175435, 0.4176561, 0.4177743, 0.4178945, 
  0.4180133, 0.4181271, 0.4182322, 0.4183252, 0.4184301, 0.4185647, 
  0.4187166, 0.4188734, 0.4190225, 0.4191516, 0.4192480, 0.4192995, 
  0.4193022, 0.4192707, 0.4192201, 0.4191651, 0.4191207, 0.4191017, 
  0.4191231, 0.4191997, 0.4192655))

which(smoothed_auto == 0.4167147)

match(0.4167147, smoothed_auto)

Output:

> smoothed_auto <- as.vector(c(0.4167147, 0.4168202, 0.4169259, 0.4170314, 0.4171361, 0.4172395, 
+   0.4173410, 0.4174401, 0.4175435, 0.4176561, 0.4177743, 0.4178945, 
+   0.4180133, 0.4181271, 0.4182322, 0.4183252, 0.4184301, 0.4185647, 
+   0.4187166, 0.4188734, 0.4190225, 0.4191516, 0.4192480, 0.4192995, 
+   0.4193022, 0.4192707, 0.4192201, 0.4191651, 0.4191207, 0.4191017, 
+   0.4191231, 0.4191997, 0.4192655))
> which(smoothed_auto == 0.4167147)
[1] 1
> match(0.4167147, smoothed_auto)
[1] 1
TarJae
  • 72,363
  • 6
  • 19
  • 66