Why does a double / numeric value in a matrix return an incorrect answer using% in% a range?

I found that integer and double values ​​behave differently in the matrix and the wrong answer returned for only two data types.

#Test m <- matrix(1:12,4,3) which(!m[1,] %in% 1:5) which(!m[1,] %in% 1:5) [1] 3 

However, when I changed the values ​​in double / numeric,

 m <- matrix(c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6), 4,3) which(!m[1,] %in% 0.10:0.35) [,1] [,2] [,3] [1,] 0.1 0.5 0.3 [2,] 0.2 0.6 0.4 [3,] 0.3 0.1 0.5 [4,] 0.4 0.2 0.6 which(!m[1,] %in% 0.10:0.35) [1] 2 3 

there should be only 2 in the answer, because 1.3 are in the range from 0.10 to 0.35, why in the calculation they differ using integer and numerical. Thanks!

+6
source share
1 answer

This is because you have an incorrect understanding of what the operator does : : Does not indicate a range, but is actually a shortcut for generating sequences of discrete values ​​(with integer intervals).

For comparison:

 > 1:5 [1] 1 2 3 4 5 > 0.1:0.35 [1] 0.1 

So, your first bit of code checks to see if %in% range of integers from 1 to 5. But the second bit of code checks to see if your data is 0.1.

To get the result, you need to write the following:

 which(!(m[1, ] >= 0.1 & m[1, ] <= 0.35)) [1] 2 
+9
source

Source: https://habr.com/ru/post/890029/


All Articles