1

I am trying below code in R and expect both conditional statements to give same result but that is not the case. Please help to understand this behaviour.

> a
[1] 23 34 45 43
> b
[1] 45 34
> c
[1] 34 45
> a == b
[1] FALSE  TRUE  TRUE FALSE
> a == c
[1] FALSE FALSE FALSE FALSE
  • 4
    *Why* do you expect both statements to give the same result? You are comparing different values, after all! – Konrad Rudolph Apr 28 '20 at 15:26
  • 2
    You probably want `a %in% b` and `a %in% c`. It would be helpful if you could say what you are expecting – MrFlick Apr 28 '20 at 15:30
  • Hi Flick, I realise we can use %in% but I just wanted to know why the results are different. I expected that they should both give same result but the cyclical repetition responses, resolves my query. – Shreyasi kalra Apr 29 '20 at 08:22

2 Answers2

1

Note that b and c are shorter than a. When you run a==b, R will adjust the length b to the same as a in a cyclical manner, say, c(23,34,45,43) == c(45,34,45,34), which gives what you see

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

Your vectors are being "recycled". This means the shorter vector is being extended by repeating itself until it matches the length of the longest. That happens when you compare (or do other kind of related arithmetic) with two or more vectors of different length.

So, when you e.g. compare your vectors a and b,

c(23, 34, 45, 43) == c(45, 34)

you're actually comparing

c(23, 34, 45, 43) == c(45, 34, 45, 34)

which is:

# [1] FALSE  TRUE  TRUE FALSE
jay.sf
  • 60,139
  • 8
  • 53
  • 110