Is there a difference between "=" and "<-",

Possible duplicate:
Assignment Operators in R: '=' and '<-'

I was wondering if there is a technical difference between the assignment operators "=" and "<-" in R. Thus, does it matter if I use:

Example 1: a = 1 or a <- 1

Example 2: a = c(1:20) or a <- c(1:20)

thanks for the help

Sven

+4
source share
1 answer

Yes there is. This help page '=' says:

The operators <- and = are assigned in the environment in which they are evaluated. The <- operator can be used anywhere, while the = operator is allowed only at the top level (for example, in the full expression typed on the command line) or as one of the subexpressions in the brackets of the expression list.

Using the "can use" help file means assigning an object here. In a function call, you cannot assign an object with = , because = means assigning arguments there.

Basically, if you use <- , then you assign a variable that you can use in your current environment. For example, consider:

 matrix(1,nrow=2) 

It just makes a 2 row matrix. Now consider:

 matrix(1,nrow<-2) 

It also gives two row matrices, but now we also have an object named nrow , which evaluates to 2! It so happened that in the second use we did not assign the argument nrow 2, we assigned the object nrow 2 and sent it to the second argument matrix , which, as it turned out, is nrow.

Edit:

Regarding edited questions. Both are the same. Using = or <- can lead to a lot of discussion about which one is better. Many style guides protect <- , and I agree with that, but keep spaces around the <- assignments, or they can become quite difficult to interpret. If you don't use spaces (you should, with the exception of twitter), I prefer = and never use -> !

But it really doesn't matter what you use if you agree on your choice. Using = on one line and <- on the following results in very ugly code.

+11
source

All Articles