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?
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?
=
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"