Hi, I'm somewhat new to R and I'm trying to figure out the difference between the operators <- and =. I've noticed that <- cannot be used to bind arguments to values in function definitions and calls. That is, f(x <- 2) sets x to 2 in the calling frame and then calls f(2) because the expression x <- 2 returns a value of 2, whereas f(x = 2) sets x = 2 in the evaluation frame and not in the calling frame. From what I can tell, = is only different than <- in the context of function definitions and calls. Is there any reason for using one operator over the other outside of function definitions and calls? Can someone point me to a precise specification of what each operator does? Any help would be appreciated! Levi
Levi Larkey schrieb:> Hi, > > I'm somewhat new to R and I'm trying to figure out the difference > between the operators <- and =.<- is an assignement operator = is primarily used for named arguments Some thoughts about the use of = as assignement operator can be found on: http://developer.r-project.org/equalAssign.html Thomas
Levi Larkey <larkey at mail.utexas.edu> wrote:
a perfect illustration of why allowing "=" as an alternative
spelling for "<-" was always an obviously really bad idea.
Is there any reason for using one operator over the other outside of
function definitions and calls?
You should never use "=" for assignment unless you are suffering such
severe "C" withdrawal symptoms that the doctor just had to give you a
shot to calm you down. It is best to keep different symbols for
different purposes. (I note that Ada uses ":=" for assignment and
"=>" for keyword arguments.)
Something that would be quite useful would be an option asking R to
warn you
- if you have any assignment operator in a function argument
(thanks to lazy evaluation this probably *won't* do what you
expect)
- if you have "=" anywhere except for binding a name to an
argument.
Perhaps these could be two options.
Spencer Graves <spencer.graves at PDF.COM> wrote:
A common, punishing error for me, with DF being a data frame, is the
following:
if(DF$a = 1) ...
where I intended to write "if(DF$a == 1)...".
This is a syntax error in R.
> d <- data.frame(a=2,b=3,c=4)
> if (d$a=1) cat("foo!")
Error: syntax error
If I've understood the R documentation correctly, "=" is only
allowed
as a synonym for "<-" at "statement" level.
Of course, that's one more reason not to use "=" when you DO want
assignment; "<-" has no such restriction.