Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are `=` and `<-` exactly the same in R? [duplicate]

Is it just a style preference?

As far as I can tell, they are the same.

I see many people prefer the "longer" <- version and I can't tell why (perhaps keeping away from = and == confusions?)

like image 587
David B Avatar asked Aug 08 '10 09:08

David B


People also ask

What is difference between <- and in R?

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

What does equals mean in R?

The Equality Operator == Relational operators, or comparators, are operators which help us see how one R object relates to another. For example, you can check whether two objects are equal (equality) by using a double equals sign == .

What is the assignment operator in R?

Assignment Operator In R, the main and most used by R users is left-arrow operator ( <- ). The obj <- expr means “assign the value of the result from the operation on the right hand side ( expr ) to the object on the left hand side ( obj )”.

Can I use equals in R?

Assigning values to variables You know, x = 3 means that x now holds the value of 3. To add to the potential confusion, the equals sign actually can be used as an assignment operator in R — most (but not all) of the time.


1 Answers

No, they are not exactly the same: the = operator cannot be used everywhere that <- can.

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

There are also differences in scope. See this answer for more details.

Which is better depends on who you ask.


Reading from "Introducing Monte Carlo Methods with R", by Robert and Casella:

"The assignment operator is =, not to be confused with ==, which is the Boolean operator for equality. An older assignment operator is <- and, for compatibility reasons, it still remains functional, but it should be ignored to ensure cleaner programming. (As pointed out by Spector, P. (2009). 'Data Manipulation with R' - Section 8.7., an exception is when using system.time, since = is then used to identify keywords)

Source


On the other hand, Google's R style guide recommends using <-:

Assignment

Use <-, not =, for assignment.

GOOD:
x <- 5

BAD:
x = 5

like image 112
Mark Byers Avatar answered Oct 18 '22 02:10

Mark Byers