r difference between <- and = code example
Example 1: r difference between <- and =
# Short answer:
# Both can be used for assignment and function similarly most of the time
# Longer answer:
# In R’s syntax the symbol = has two distinct meanings that frequently
# get conflated. They are:
1. The first meaning of = is as an assignment operator
2. The second meaning of = is as a syntax token that signals named
argument passing in a function call. Unlike the = operator it
performs no action at runtime, it merely changes the way an
expression is parsed
# With regards to assignment, the only difference is their operator
# precedence. Operator precedence priority goes from top to bottom:
-> or ->> assignment (left to right) # Weirdness
<- or <<- assignment (right to left)
= assignment (right to left)
# With regards to named argument passing, the main thing to know is that
# = was designed to be used at the top level, meaning outside of
# subexpressions such as if statements or functions. However, you can
# get around this by adding an extra set of parentheses when you use =
# For example:
# If x is undefined and you use it in a function like this, you will get
# an error:
median(x = 1:10)
# But, both of these syntaxes work:
median((x = 1:10))
median(x <- 1:10)
# If you're getting errors like these, you are probably not following
# this advice
Error: unexpected '=' in <blah> or
Error in <blah> : argument <blah> is missing, with no default
Example 2: R difference | and
||# Operators & and | perform element-wise operation producing
# result having length of the longer operand.
# But && and || examines only the first element of the operands
resulting into a single length logical vector.