Assignment Operators
Assignment stores a value under a name, like putting a toy into a labeled box using an arrow. R usually draws the arrow pointing left.
In this page:
Syntax
variable_name <- value
variable_name = value
value -> variable_name
Assignment Operators
R conventionally uses <- for assignment, though = also works in most contexts.
<- is preferred by style guides because it's unambiguous everywhere, including inside function calls where = has a different meaning (naming an argument). The right-pointing -> is also valid and assigns from left to right.
Warning:
Inside a function call,
f(x = 1) sets a named argument, not a variable assignment -- use <- when you actually mean assignment.Example: Assignment Operators
x <- 10
y = 20
30 -> z
cat(x, y, z, "\n")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
->in a way that reads backwards, as in30 -> z, and confusing which side receives the value. - Writing
x < - 5with a space, which is a comparison ofxwith-5rather than an assignment. - Using
=inside a function call such asmean(x = 5)and expecting a global variablexto be created, when it only sets an argument.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: