开发者

Why double/numeric value in matrix return wrong answer by using %in% a range?

开发者 https://www.devze.com 2023-03-11 15:00 出处:网络
I found integer and double values behaves differently in matrix and wrong answer returnedfor double data types only.

I found integer and double values behaves differently in matrix and wrong answer returned for double data types only.

#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

only 2 should be in the answer because 1,3 are in the range of 0.10 to 0.35, why it is different in the computation using integer and numeric. Thanks!


It's because you have a flawed understanding of what the : operator does. : does not indicate a range, but is indeed a shortcut to generate sequences of discrete values (at integer intervals).

Compare:

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

> 0.1:0.35
[1] 0.1

So your first bit of code tests whether a value is %in% the range of integers 1 to 5. But the second bit of code tests whether your data is equal to 0.1.

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号