Home > Blockchain >  Check if two vectors have more than 600 and same index and then print the match index
Check if two vectors have more than 600 and same index and then print the match index

Time:01-28

set.seed(75)
Vec1 <- sample(0:999, size = 100)
Vec2 <- sample(0:999, size = 100)
vec2m <- which(Vec2>600)==which(Vec1>600)
print(vec2m)

used which to get index and compare it with equal to another vector but is not working

CodePudding user response:

If we are looking for common index, use intersect.

intersect(which(Vec2 > 600), which(Vec1 >600))
[1]  5  6 13 23 32 34 75 89 96

Comparing with == can be buggy here as == is elementwise comparison operator, thus it can only work correctly when the length of both the rhs and lhs are either same or one of them is of length 1, otherwise it will recycle and we get an incorrect output. e.g. here we have different lengths

> which(Vec2 > 600)
 [1]  5  6  7  9 13 14 20 22 23 25 26 28 31 32 34 35 38 41 48 50 51 52 54 65 68 75 81 83 85 89 93 96
> which(Vec1 >600)
 [1]  1  3  4  5  6  8 11 13 18 21 23 24 27 29 30 32 33 34 36 37 40 44 45 47 49 56 60 63 64 66 72 74 75 76 77 79 80 82 84 89 90 92
[43] 96 98
> which(Vec2 > 600) == which(Vec1 > 600)
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[22] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[43] FALSE FALSE
Warning message:
In which(Vec2 > 600) == which(Vec1 > 600) :
  longer object length is not a multiple of shorter object length

In the above comparison, all of them are FALSE as the 5 from the 'Vec2' index is compared with 1 from 'Vec1', then 6 with 3 and so on.

If we want a logical output, then use %in% instead of ==

> which(Vec2 > 600) %in% which(Vec1 > 600)
 [1]  TRUE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
[22] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE
  •  Tags:  
  • r
  • Related