0
x <- -3:3
x[x=2]/x[x==2] = -1

Why the numerator x[x=2] equals -2?

Can anybody explain the difference between = and == in logical indices?

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    If you see this in your code base there is a >99% chance it's a typo and therefore a bug. – Roland Jul 13 '18 at 07:53

1 Answers1

3

= is doing assignment here, not comparison. When you do assignment, by default the right hand side value is returned. Observe

print(x=2)
# [1] 2
print(x=100)
# [1] 100
print(x<-2)
# [1] 2

so it's the same as

x[2]/x[x==2]

and

x[2]
# [1] -2

so -2/2 is -1.

You should generally avoid = except for naming parameters passed to functions. Use <- for assignment, and == for comparison. That way when you see a = in [] it jumps out as being "wrong"

IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38
MrFlick
  • 195,160
  • 17
  • 277
  • 295