right assignment in r

Secure Your Spot in Our Statistical Methods in R Online Course Starting on September 9 (Click for More Info)

Joachim Schork Image Course

Assignment Operators in R (3 Examples) | Comparing = vs. <- vs. <<-

On this page you’ll learn how to apply the different assignment operators in the R programming language .

The content of the article is structured as follows:

Let’s dive right into the exemplifying R syntax!

Example 1: Why You Should Use <- Instead of = in R

Generally speaking, there is a preference in the R programming community to use an arrow (i.e. <-) instead of an equal sign (i.e. =) for assignment.

In my opinion, it makes a lot of sense to stick to this convention to produce scripts that are easy to read for other R programmers.

However, you should also take care about the spacing when assigning in R. False spacing can even lead to error messages .

For instance, the following R code checks whether x is smaller than minus five due to the false blank between < and -:

A properly working assignment could look as follows:

However, this code is hard to read, since the missing space makes it difficult to differentiate between the different symbols and numbers.

In my opinion, the best way to assign in R is to put a blank before and after the assignment arrow:

As mentioned before, the difference between <- and = is mainly due to programming style . However, the following R code using an equal sign would also work:

In the following example, I’ll show a situation where <- and = do not lead to the same result. So keep on reading!

Example 2: When <- is Really Different Compared to =

In this Example, I’ll illustrate some substantial differences between assignment arrows and equal signs.

Let’s assume that we want to compute the mean of a vector ranging from 1 to 5. Then, we could use the following R code:

However, if we want to have a look at the vector x that we have used within the mean function, we get an error message:

Let’s compare this to exactly the same R code but with assignment arrow instead of an equal sign:

The output of the mean function is the same. However, the assignment arrow also stored the values in a new data object x:

This example shows a meaningful difference between = and <-. While the equal sign doesn’t store the used values outside of a function, the assignment arrow saves them in a new data object that can be used outside the function.

Example 3: The Difference Between <- and <<-

So far, we have only compared <- and =. However, there is another assignment method we have to discuss: The double assignment arrow <<- (also called scoping assignment).

The following code illustrates the difference between <- and <<- in R. This difference mainly gets visible when applying user-defined functions .

Let’s manually create a function that contains a single assignment arrow:

Now, let’s apply this function in R:

The data object x_fun1, to which we have assigned the value 5 within the function, does not exist:

Let’s do the same with a double assignment arrow:

Let’s apply the function:

And now let’s return the data object x_fun2:

As you can see based on the previous output of the RStudio console, the assignment via <<- saved the data object in the global environment outside of the user-defined function.

Video & Further Resources

I have recently released a video on my YouTube channel , which explains the R syntax of this tutorial. You can find the video below:

The YouTube video will be added soon.

In addition to the video, I can recommend to have a look at the other articles on this website.

  • R Programming Examples

In summary: You learned on this page how to use assignment operators in the R programming language. If you have further questions, please let me know in the comments.

assignment-operators-in-r How to use different assignment operators in R – 3 R programming examples – R programming language tutorial – Actionable R programming syntax in RStudio

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy .

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Post Comment

Joachim Schork Statistician Programmer

I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.

Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy .

Related Tutorials

sugar Functions in Rcpp Package in R (Example)

sugar Functions in Rcpp Package in R (Example)

Access Attributes of Data Object in R (2 Examples)

Access Attributes of Data Object in R (2 Examples)

assignOps {base}R Documentation

Assignment Operators

Description.

Assign a value to a name.

a variable name (possibly quoted).

a value to be assigned to .

There are three different assignment operators: two of them have leftwards and rightwards forms.

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.

The operators <<- and ->> are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment. Note that their semantics differ from that in the S language, but are useful in conjunction with the scoping rules of R . See ‘The R Language Definition’ manual for further details and examples.

In all the assignment operator expressions, x can be a name or an expression defining a part of an object to be replaced (e.g., z[[1]] ). A syntactic name does not need to be quoted, though it can be (preferably by backtick s).

The leftwards forms of assignment <- = <<- group right to left, the other from left to right.

value . Thus one can use a <- b <- c <- 6 .

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language . Wadsworth & Brooks/Cole.

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language . Springer (for = ).

assign (and its inverse get ), for “subassignment” such as x[i] <- v , see [<- ; further, environment .

Blog of Ken W. Alger

Just another Tech Blog

Blog of Ken W. Alger

Assignment Operators in R – Which One to Use and Where

right assignment in r

Assignment Operators

R has five common assignment operators:

Many style guides and traditionalists prefer the left arrow operator, <- . Why use that when it’s an extra keystroke?  <- always means assignment. The equal sign is overloaded a bit taking on the roles of an assignment operator, function argument binding, or depending on the context, case statement.

Equal or “arrow” as an Assignment Operator?

In R, both the equal and arrow symbols work to assign values. Therefore, the following statements have the same effect of assigning a value on the right to the variable on the left:

There is also a right arrow, -> which assigns the value on the left, to a variable on the right:

All three assign the  value of forty-two to the  variable   x .

So what’s the difference? Are these assignment operators interchangeable? Mostly, yes. The difference comes into play, however, when working with functions.

The equal sign can also work as an operator for function parameters.

x <- 42 y <- 18 function(value = x-y)

History of the <- Operator

right assignment in r

The S language also didn’t have == for equality testing, so that was left to the single equal sign. Therefore, variable assignment needed to be accomplished with a different symbol, and the arrow was chosen.

There are some differences of opinion as to which assignment operator to use when it comes to = vs <-. Some believe that = is more clear. The <- operator maintains backward compatibility with S.  Google’s R Style Guide recommends using the <- assignment operator, which seems to be a pretty decent reason as well. When all is said and done, though, it is like many things in programming, it depends on what your team does.

right assignment in r

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to print (Opens in new window)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

assignOps: Assignment Operators

assignOpsR Documentation

Assignment Operators

Description.

Assign a value to a name.

a variable name (possibly quoted).

a value to be assigned to .

There are three different assignment operators: two of them have leftwards and rightwards forms.

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.

The operators <<- and ->> are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment. Note that their semantics differ from that in the S language, but are useful in conjunction with the scoping rules of R . See ‘The R Language Definition’ manual for further details and examples.

In all the assignment operator expressions, x can be a name or an expression defining a part of an object to be replaced (e.g., z[[1]] ). A syntactic name does not need to be quoted, though it can be (preferably by backticks).

The leftwards forms of assignment <- = <<- group right to left, the other from left to right.

value . Thus one can use a <- b <- c <- 6 .

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language . Wadsworth & Brooks/Cole.

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language . Springer (for = ).

assign (and its inverse get ), for “subassignment” such as x[i] <- v , see [<- ; further, environment .

R Package Documentation

Browse r packages, we want your feedback.

right assignment in r

Add the following code to your website.

REMOVE THIS Copy to clipboard

For more information on customizing the embed code, read Embedding Snippets .

Assignment Operators in R

R provides two operators for assignment: <- and = .

Understanding their proper use is crucial for writing clear and readable R code.

Using the <- Operator

For assignments.

The <- operator is the preferred choice for assigning values to variables in R.

It clearly distinguishes assignment from argument specification in function calls.

Readability and Tradition

  • This usage aligns with R’s tradition and enhances code readability.

Using the = Operator

The = operator is commonly used to explicitly specify named arguments in function calls.

It helps in distinguishing argument assignment from variable assignment.

Assignment Capability

  • While = can also be used for assignment, this practice is less common and not recommended for clarity.

Mixing Up Operators

Potential confusion.

Using = for general assignments can lead to confusion, especially when reading or debugging code.

Mixing operators inconsistently can obscure the distinction between assignment and function argument specification.

  • In the example above, x = 10 might be mistaken for a function argument rather than an assignment.

Best Practices Recap

Consistency and clarity.

Use <- for variable assignments to maintain consistency and clarity.

Reserve = for specifying named arguments in function calls.

Avoiding Common Mistakes

Be mindful of the context in which you use each operator to prevent misunderstandings.

Consistently using the operators as recommended helps make your code more readable and maintainable.

Quiz: Assignment Operator Best Practices

Which of the following examples demonstrates the recommended use of assignment operators in R?

  • my_var = 5; mean(x = my_var)
  • my_var <- 5; mean(x <- my_var)
  • my_var <- 5; mean(x = my_var)
  • my_var = 5; mean(x <- my_var)
  • The correct answer is 3 . my_var <- 5; mean(x = my_var) correctly uses <- for variable assignment and = for specifying a named argument in a function call.
assignOps {base}R Documentation

Assignment Operators

Description.

Assign a value to a name.

a variable name (possibly quoted).
a value to be assigned to .

There are three different assignment operators: two of them have leftwards and rightwards forms.

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.

The operators <<- and ->> cause a search to made through the environment for an existing definition of the variable being assigned. If such a variable is found then its value is redefined, otherwise assignment takes place globally. Note that their semantics differ from that in the S language, but are useful in conjunction with the scoping rules of R . See ‘The R Language Definition’ manual for further details and examples.

In all the assignment operator expressions, x can be a name or an expression defining a part of an object to be replaced (e.g., z[[1]] ). The name does not need to be quoted, though it can be.

The leftwards forms of assignment <- = <<- group right to left, the other from left to right.

value . Thus one can use a <- b <- c <- 6 .

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language . Wadsworth & Brooks/Cole.

Chamber, J. M. (1998) Programming with Data. A Guide to the S Language . Springer (for = ).

assign , environment .

assign_ops {roperators}R Documentation

Assignment operators

Description.

Modifies the stored value of the left-hand-side object by the right-hand-side object. Equivalent of operators such as += -= *= /= in languages like c++ or python. %+=% and %-=% can also work with strings.

a stored value

value to modify stored value by

Ben Wiseman, [email protected]

  • R - Introduction
  • R - Comments
  • R - Variables
  • R - Data Types
  • R - Data Structures
  • R - Operators
  • R - If Else
  • R - Switch Statement
  • R - While Loop
  • R - For Loop
  • R - Repeat Loop
  • R - Next Statement
  • R - Break Statement
  • R - Functions
  • R - Scope of Variables
  • R - Pie Chart
  • R - Bar Plot
  • R - Line Graph
  • R - Histogram
  • R - Scatter Plot
  • R - Box Plot
  • R - Dendrogram
  • R - Mean, Median & Mode
  • R - Normal Distribution
  • R - Binomial Distribution
  • R - Geometric Distribution
  • R - Logistic Distribution
  • R - Exponential Distribution
  • R - Uniform Distribution
  • R - Poisson Distribution
  • R - Weibull Distribution
  • R - Math Functions
  • R - Statistical Functions
  • R - String Functions
  • R - Examples

AlphaCodingSkills

Facebook Page

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

R - right assignment operator example

Right Assignment operator assigns value of right hand side expression to right hand side operand. R has two such kind of operators (-> and ->>).

Right assignment operator (->)

It assigns value of left hand side expression to right hand side operand.

The output of the above code will be:

Right assignment operator (->>)

It assigns value of left hand side expression to right hand side operand. It has same functionality as (->) but as global assignment operator.

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

R-bloggers

R news and tutorials contributed by hundreds of R bloggers

Why do we use arrow as an assignment operator.

Posted on September 23, 2018 by Colin Fay in R bloggers | 0 Comments

[social4i size="small" align="align-left"] --> [This article was first published on Colin Fay , and kindly contributed to R-bloggers ]. (You can report issue about the content on this page here ) Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

A Twitter Thread turned into a blog post.

In June, I published a little thread on Twitter about the history of the <- assignment operator in R. Here is a blog post version of this thread.

Historical reasons

As you all know, R comes from S. But you might not know a lot about S (I don’t). This language used <- as an assignment operator. It’s partly because it was inspired by a language called APL, which also had this sign for assignment.

But why again? APL was designed on a specific keyboard, which had a key for <- :

At that time, it was also chosen because there was no == for testing equality: equality was tested with = , so assigning a variable needed to be done with another symbol.

right assignment in r

From APL Reference Manual

Until 2001 , in R, = could only be used for assigning function arguments, like fun(foo = "bar") (remember that R was born in 1993). So before 2001, the <- was the standard (and only way) to assign value into a variable.

Before that, _ was also a valid assignment operator. It was removed in R 1.8 :

right assignment in r

(So no, at that time, no snake_case_naming_convention)

Colin Gillespie published some of his code from early 2000 , where assignment was made like this 🙂

The main reason “equal assignment” was introduced is because other languages uses = as an assignment method, and because it increased compatibility with S-Plus.

Readability

Nowadays, there are seldom any cases when you can’t use one in place of the other. It’s safe to use = almost everywhere. Yet, <- is preferred and advised in R Coding style guides:

  • https://google.github.io/styleguide/Rguide.xml#assignment
  • http://adv-r.had.co.nz/Style.html

One reason, if not historical, to prefer the <- is that it clearly states in which side you are making the assignment (you can assign from left to right or from right to left in R):

The RHS assignment can for example be used for assigning the result of a pipe

Also, it’s easier to distinguish equality comparison and assignment in the last line of code here:

Note that <<- and ->> also exist:

And that Ross Ihaka uses = : https://www.stat.auckland.ac.nz/~ihaka/downloads/JSM-2010.pdf

Environments

There are some environment and precedence differences. For example, assignment with = is only done on a functional level, whereas <- does it on the top level when called inside as a function argument.

In the first code, you’re passing x as the parameter of the median function, whereas the second one is creating a variable x in the environment, and uses it as the first argument of median . Note that it works because x is the name of the parameter of the function, and won’t work with y :

There is also a difference in parsing when it comes to both these operators (but I guess this never happens in the real world), one failing and not the other:

It is also good practice because it clearly indicates the difference between function arguments and assignation:

And this weird behavior:

Little bit unrelated but

I love this one:

Which of course is not doable with = .

Other operators

Some users pointed out on Twitter that this could make the code a little bit harder to read if you come from another language. <- is use “only” use in F#, OCaml, R and S (as far as Wikipedia can tell). Even if <- is rare in programming, I guess its meaning is quite easy to grasp, though.

Note that the second most used assignment operator is := ( = being the most common). It’s used in {data.table} and {rlang} notably. The := operator is not defined in the current R language, but has not been removed, and is still understood by the R parser. You can’t use it on the top level:

But as it is still understood by the parser, you can use := as an infix without any %%, for assignment, or for anything else:

You can see that := was used as an assignment operator https://developer.r-project.org/equalAssign.html :

All the previously allowed assignment operators (

Or in R NEWS 1:

right assignment in r

  • Around 29’: https://channel9.msdn.com/Events/useR-international-R-User-conference/useR2016/Forty-years-of-S
  • What are the differences between “=” and “
  • Assignment Operators

To leave a comment for the author, please follow the link and comment on their blog: Colin Fay . R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job . Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Copyright © 2022 | MH Corporate basic by MH Themes

Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts. (You will not see this message again.)

Logical, Comparision, Assignment and Arithmetic Operators in R

Assignment operators in r, comparison operators, logical operators, arithmetic operators, miscellaneous operators in r.

right assignment in r

StevenSwiniarski's avatar

Operators are used in R to perform various operations on variables and values. Among the most commonly used ones are arithmetic and assignment operators.

The following R code uses an arithmetic operator for multiplication, * , to calculate the product of two numbers, along with the assignment operator, <- to store the result in the variable x .

Operators in R can be organized into the following groups:

  • Arithmetic operators for traditional mathematical evaluations such as addition and subtraction.
  • Assignment operators for assigning values to variables.
  • Comparison operators for testing equality between values.
  • Logical operators for evaluating the “truthiness” of values against one another.
  • Miscellaneous operators for various tasks including vectors and sequencing.

Arithmetic operators

R supports the following arithmetic operators:

  • Addition, + , which returns the sum of two numbers.
  • Subtraction, - , which returns the difference between two numbers.
  • Multiplication, * , which returns the product of two numbers.
  • Division, / , which returns the quotient of two numbers.
  • Exponents, ^ , which returns the value of one number raised to the power of another.
  • Modulus, %% , which returns the remainder of one number divided by another.
  • Integer Division, %/% , which returns the integer quotient of two numbers.

Assignment operators

R uses the following assignment operators:

  • <- assigns a value to a variable from right to left.
  • -> assigns a value to a variable left to right.
  • <<- is a global version of <- .
  • ->> is a global version of -> .
  • = works the same way as <- , but its use is discouraged.

Comparison operators

R has the following comparison operators:

  • Equal, == , which returns TRUE if two values are equal.
  • Not equal, != , which returns TRUE if two values are not equal.
  • Less than, < , which returns TRUE if left value is less than right value.
  • Less than or equal to, <= , which returns TRUE if left value is less than or equal to right value.
  • Greater than, > , which returns TRUE if left value is greater than right value.
  • Greater than or equal to, >= , which returns TRUE if left value is greater than or equal to right value.

Logical operators

R has the following logical operators:

  • Element-wise AND, & , for comparing each element and returning TRUE if both elements are TRUE .
  • Logical AND, && , which returns TRUE if both values are TRUE , only evaluates as many elements as necessary.
  • Element-wise OR, | , for comparing each element and returning TRUE if either element is TRUE .
  • Logical OR, || , which returns TRUE if either value is TRUE , only evaluates as many elements as necessary.
  • Logical NOT, ! , which returns TRUE if the associated statement is FALSE .

Note: The long form of AND and OR ( && and || ) are preferred for if statements as the short form can produce a vector value.

Miscellaneous operators

R uses the following miscellaneous operators:

  • The : operator creates a sequence of numbers from the left argument to the right one.
  • The %in% operator returns TRUE if the left argument is in the vector to the right.
  • The %*% operator performs matrix multiplication on two matrices.

All contributors

Looking to contribute.

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Learn R on Codecademy

Computer science.

Popular Tutorials

Popular examples, learn python interactively, r introduction.

  • R Reserved Words
  • R Variables and Constants

R Operators

  • R Operator Precedence and Associativitys

R Flow Control

  • R if…else Statement

R ifelse() Function

  • R while Loop
  • R break and next Statement
  • R repeat loop
  • R Functions
  • R Return Value from Function
  • R Environment and Scope
  • R Recursive Function

R Infix Operator

  • R switch() Function

R Data Structures

  • R Data Frame

R Object & Class

  • R Classes and Objects
  • R Reference Class

R Graphs & Charts

  • R Histograms
  • R Pie Chart
  • R Strip Chart

R Advanced Topics

  • R Plot Function
  • R Multiple Plots
  • Saving a Plot in R
  • R Plot Color

Related Topics

R Operator Precedence and Associativity

R Program to Add Two Vectors

In this article, you will learn about different R operators with the help of examples.

R has many operators to carry out different mathematical and logical operations. Operators perform tasks including arithmetic, logical and bitwise operations.

  • Type of operators in R

Operators in R can mainly be classified into the following categories:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Assignment Operators
  • R Arithmetic Operators

These operators are used to carry out mathematical operations like addition and multiplication. Here is a list of arithmetic operators available in R.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponent
%% Modulus(Remainder from division)
%/% Integer Division

Let's look at an example illustrating the use of the above operators:

  • R Relational Operators

Relational operators are used to compare between values. Here is a list of relational operators available in R.

Operator Description
Less than
> Greater than
Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Let's see an example for this:

  • Operation on Vectors

The above mentioned operators work on vectors . The variables used above were in fact single element vectors.

We can use the function c() (as in concatenate) to make vectors in R.

All operations are carried out in element-wise fashion. Here is an example.

When there is a mismatch in length (number of elements) of operand vectors, the elements in the shorter one are recycled in a cyclic manner to match the length of the longer one.

R will issue a warning if the length of the longer vector is not an integral multiple of the shorter vector.

  • R Logical Operators

Logical operators are used to carry out Boolean operations like AND , OR etc.

Operator Description
! Logical NOT
& Element-wise logical AND
&& Logical AND
| Element-wise logical OR
|| Logical OR

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 in a single length logical vector.

Zero is considered FALSE and non-zero numbers are taken as TRUE . Let's see an example for this:

  • R Assignment Operators

These operators are used to assign values to variables.

Operator Description
Leftwards assignment
->, ->> Rightwards assignment

The operators <- and = can be used, almost interchangeably, to assign to variables in the same environment.

The <<- operator is used for assigning to variables in the parent environments (more like global assignments). The rightward assignments, although available, are rarely used.

Check out these examples to learn more:

  • Add Two Vectors
  • Take Input From User
  • R Multiplication Table

Table of Contents

  • Introduction

Sorry about that.

R Tutorials

Programming

Skip navigation

A Step to the Right in R Assignments

  • 2015-02-04 – 15:27
  • Posted in Programming , R
  • Tagged post

I received an out-of-band question on the use of `%<>%` in my [CDC FluView](rud.is/b/2015/01/10/new-r-package-cdcfluview-retrieve-flu-data-from-cdcs-fluview-portal/) post, and took the opportunity to address it in a broader, public fashion.

(which is from the `magrittr` documentation).

To avoid the repetition of the left-hand side immediately after the assignment operator, Bache & Wickham came up with the `%<>%` operator, which shortens the above to:

Try as I may (including the CDC FluView blog post), that way of assigning variables still _feels_ awkward, and is definitely confusing to new R users. But, what’s the alternative? I believe it’s R’s infrequently used `->` RHS assignment operator.

Let’s look at that in the context of the somewhat-long pipe in the CDC FluView example:

That pipe flow says _”take `dat`, change-up some columns, make some new columns and reassign into `dat`”_. It’s a very natural flow and reads well, too, since you’re following a process up to it’s final destination. It’s even more natural in pipes that actually transform the data into something else. For example, to get a vector of the number of US male births since 1880, we’d do:

That’s very readable (one of the benefits of pipes) and the flow, again, makes sense. Compare that to it’s base R counterpart:

The base R version is short and the LHS assignment fits well as the values “pop out” of the function calls. But, it’s also only initially, quickly readable to veteran R folks. Since code needs to be readable, maintainable and (often times) shared with folks on a team, I believe the pipes help increase overall productivity and aid in documenting what is trying to be achieved in that portion of an analysis (especially when combined with `dplyr` idioms).

Pipes are here to stay and they are definitely a part of my data analysis workflows. Moving forward, so will RHS (`->`) assignments from pipes.

Share this:

12 comments.

' src=

  • Posted 2015-02-05 at 04:50

Yes! I’ve kind of got the hang of it now, but when I was first trying to read pipes the switch in direction was really making it unintuitive. %<>% only solves the case where you want to alter the input, -> is much more general.

' src=

  • Posted 2015-02-05 at 12:35

I’ve been using ‘%<>%’ a lot in my code lately, mostly because I had no idea that ‘->’ existed. Thanks very much!

' src=

  • Posted 2015-02-05 at 13:19

Interesting, good point that you make! I also wasn’t too happy with the currently practiced solutions, and I had no idea there is a RHS assignment operator either… maybe I’m going to give it a try!

' src=

  • Posted 2015-02-05 at 18:41

Glad I’m not the only one who’s faced this dilemma! Using the backward assignment operator has also become my main solution as well.

It might be nice for dplyr or magrittr to add an enhanced assign function (assign_to??), that’s first argument is the value, second argument is the unquoted name, and the third argument is the environment with a default value of the parent environment.

' src=

  • Posted 2015-02-05 at 19:31

I prefer %<>% and <- for the simple reason that it’s easy to look along the left gutter and see what I’ve assigned.

While there’s a logical consistency to “flowing” a pipe to ->, in your example with the assignment to males , I would never know that existed if I were further down in the code. With males locked on the left hand side, it’s easy to see which objects exist. Otherwise, how do I know I assigned it to males versus reassigning to the same starting frame like in the dat example?

' src=

  • Posted 2015-02-05 at 21:29

I have a special can opener just for cans of worms ;-). But seriously, I’ve been programming a long time and I’ve always been a fan of right-pointing assignment. It’s the STORE operation in assembler, fercryinoutloud!

But IIRC the R folks deprecated it a while back Have they un-deprecated it or are we right-assigners doomed to piss into a gale? ;-)

' src=

  • Posted 2015-02-06 at 03:12

Interesting discussion. However, I do disagree: https://gist.github.com/smbache/ae9fb6bb747ac4f23a78

' src=

  • Posted 2015-02-06 at 08:58

I’m very much with Stefan here — I think the RHS operator is dangerous, especially if one is trying to understand code, as one only discovers at the end whether there is an operation happening or an assignment.

  • Posted 2015-02-09 at 09:12

You might have a point there.

' src=

  • Posted 2015-02-09 at 17:23

Where I was using magrittr and using a format like

noun %>% verb %>% verb -> noun

it felt quite natural to use the RHS version.

However, I think in longer chunks of code, function building etc it would prove tougher for comprehensibility. I also try to make code accessible for beginners so I always try to be consistent by using the LHS assignment, and never = , therefore the RHS will probably not make showings outside of quick scripts for me.

' src=

  • Posted 2016-05-26 at 06:28

Just came across this discussion, as I have been thinking along similar lines. I wrote a function that exactly satisfies Jamie’s suggestion. Code and motivation are here: http://jepusto.github.io//assigning-after-dplyr

This won’t get incorporated into dplyr or magrittr, but perhaps useful for folks who find -> sensible…

' src=

  • Posted 2016-08-11 at 21:07

I agree with this on sooo many levels! This is much more natural.

One Trackback/Pingback

[…] But David Smith in “Use = or <- for assignment?” argues for <-. And Bob Rudis in “A Step to the Right in R Assignments” argues for yet another permitted symbol, ->, because it fits better with the Tidyverse’s […]

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Cover image from Data-Driven Security

  • Cookie Policy • Privacy Policy
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How do you use "<<-" (scoping assignment) in R?

I just finished reading about scoping in the R intro , and am very curious about the <<- assignment.

The manual showed one (very interesting) example for <<- , which I feel I understood. What I am still missing is the context of when this can be useful.

So what I would love to read from you are examples (or links to examples) on when the use of <<- can be interesting/useful. What might be the dangers of using it (it looks easy to loose track of), and any tips you might feel like sharing.

  • lexical-scope

Bhargav Rao's user avatar

  • 1 I've used <<- to preserve key variables generated inside a function to record in failure logs when the function fails. Can help to make the failure reproducible if the function used inputs (e.g. from external APIs) that wouldn't necessarily have been preserved otherwise due to the failure. –  geotheory Commented Oct 9, 2020 at 11:59

7 Answers 7

<<- is most useful in conjunction with closures to maintain state. Here's a section from a recent paper of mine:

A closure is a function written by another function. Closures are so-called because they enclose the environment of the parent function, and can access all variables and parameters in that function. This is useful because it allows us to have two levels of parameters. One level of parameters (the parent) controls how the function works. The other level (the child) does the work. The following example shows how can use this idea to generate a family of power functions. The parent function ( power ) creates child functions ( square and cube ) that actually do the hard work.

The ability to manage variables at two levels also makes it possible to maintain the state across function invocations by allowing a function to modify variables in the environment of its parent. The key to managing variables at different levels is the double arrow assignment operator <<- . Unlike the usual single arrow assignment ( <- ) that always works on the current level, the double arrow operator can modify variables in parent levels.

This makes it possible to maintain a counter that records how many times a function has been called, as the following example shows. Each time new_counter is run, it creates an environment, initialises the counter i in this environment, and then creates a new function.

The new function is a closure, and its environment is the enclosing environment. When the closures counter_one and counter_two are run, each one modifies the counter in its enclosing environment and then returns the current count.

abbassix's user avatar

  • 6 Hey this is an unsolved R task on Rosettacode ( rosettacode.org/wiki/Accumulator_factory#R ) Well, it was... –  Karsten W. Commented Apr 15, 2010 at 15:05
  • 1 Would there be any need to enclose more than 1 closures in one parent function? I just tried one snippet, it seems that only the last closure was executed... –  Oliver Commented Feb 3, 2018 at 15:13
  • Is there any equal sign alternative to the "<<-" sign? –  Saren Tasciyan Commented May 1, 2019 at 15:46

It helps to think of <<- as equivalent to assign (if you set the inherits parameter in that function to TRUE ). The benefit of assign is that it allows you to specify more parameters (e.g. the environment), so I prefer to use assign over <<- in most cases.

Using <<- and assign(x, value, inherits=TRUE) means that "enclosing environments of the supplied environment are searched until the variable 'x' is encountered." In other words, it will keep going through the environments in order until it finds a variable with that name, and it will assign it to that. This can be within the scope of a function, or in the global environment.

In order to understand what these functions do, you need to also understand R environments (e.g. using search ).

I regularly use these functions when I'm running a large simulation and I want to save intermediate results. This allows you to create the object outside the scope of the given function or apply loop. That's very helpful, especially if you have any concern about a large loop ending unexpectedly (e.g. a database disconnection), in which case you could lose everything in the process. This would be equivalent to writing your results out to a database or file during a long running process, except that it's storing the results within the R environment instead.

My primary warning with this: be careful because you're now working with global variables, especially when using <<- . That means that you can end up with situations where a function is using an object value from the environment, when you expected it to be using one that was supplied as a parameter. This is one of the main things that functional programming tries to avoid (see side effects ). I avoid this problem by assigning my values to a unique variable names (using paste with a set or unique parameters) that are never used within the function, but just used for caching and in case I need to recover later on (or do some meta-analysis on the intermediate results).

Shane's user avatar

  • 4 Thanks Tal. I have a blog, although I don't really use it. I can never finish a post because I don't want to publish anything unless it's perfect, and I just don't have time for that... –  Shane Commented Apr 13, 2010 at 13:44
  • 5 A wise man once said to me it is not important to be perfect - only out standing - which you are, and so will your posts be. Also - sometimes readers help improve the text with the comments (that's what happens with my blog). I hope one day you will reconsider :) –  Tal Galili Commented Apr 13, 2010 at 15:25

One place where I used <<- was in simple GUIs using tcl/tk. Some of the initial examples have it -- as you need to make a distinction between local and global variables for statefullness. See for example

which uses <<- . Otherwise I concur with Marek :) -- a Google search can help.

Dirk is no longer here's user avatar

  • Interesting, I somehow cannot find tkdensity in R 3.6.0. –  NelsonGon Commented Jun 26, 2019 at 16:22
  • 1 The tcltk package ships with R: github.com/wch/r-source/blob/trunk/src/library/tcltk/demo/… –  Dirk is no longer here Commented Jun 26, 2019 at 16:30

On this subject I'd like to point out that the <<- operator will behave strangely when applied (incorrectly) within a for loop (there may be other cases too). Given the following code:

you might expect that the function would return the expected sum, 6, but instead it returns 0, with a global variable mySum being created and assigned the value 3. I can't fully explain what is going on here but certainly the body of a for loop is not a new scope 'level'. Instead, it seems that R looks outside of the fortest function, can't find a mySum variable to assign to, so creates one and assigns the value 1, the first time through the loop. On subsequent iterations, the RHS in the assignment must be referring to the (unchanged) inner mySum variable whereas the LHS refers to the global variable. Therefore each iteration overwrites the value of the global variable to that iteration's value of i , hence it has the value 3 on exit from the function.

Hope this helps someone - this stumped me for a couple of hours today! (BTW, just replace <<- with <- and the function works as expected).

OTStats's user avatar

  • 4 in your example, the local mySum is never incremented but only the global mySum . Hence at each iteration of the for loop, the global mySum get the value 0 + i . You can follow this with debug(fortest) . –  ClementWalter Commented Oct 26, 2015 at 16:49
  • It's got nothing to do with it being a for-loop; you're referencing two different scopes. Just use <- everywhere consistently within the function if you only want to update the local variable inside the function. –  smci Commented Apr 29, 2016 at 3:08
  • Or use <<-- everywhere @smci. Though best to avoid globals. –  Union find Commented Dec 5, 2017 at 4:15
  • As far as I understand, R is NOT scoped withing braces { }, which is different from many other languages. The scoping is within functions. So, <<- does not access the mySum outside of the for loop as you might expect; rather, it accesses mySum outside of the fortest function. In the first run, mySum did not exist outside of fortest , so it was created, initialized as zero, and then incremented. Each subsequent iteration of the for loop iterates the global mySum again. So, the mySum in fortest always stays as zero but a global mySum is created and incremented to 3. –  Tripartio Commented Jan 3 at 13:14

lcgong's user avatar

  • 12 This is a good example of where not to use <<- . A for loop would be clearer in this case. –  hadley Commented Apr 13, 2010 at 14:15

The <<- operator can also be useful for Reference Classes when writing Reference Methods . For example:

Carlos Cinelli's user avatar

I use it in order to change inside purrr::map() an object in the global environment.

Say I want to obtain a vector which is c(1,2,3,1,2,3,4,5), that is if there is a 1, let it 1, otherwise add 1 until the next 1.

Tripartio's user avatar

  • This tiny answer explains what brought me to this question--why <- often does not work in purrr::map and I have to use <<- . Now I get it: purrr::map does its work inside a function and there only function scope applies. So, super-assignment <<- is required to modify variables outside of the purrr::map internal function (the .f argument). –  Tripartio Commented Jan 3 at 13:18

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged r scoping lexical-scope r-faq or ask your own question .

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Doesn't nonlocality follow from nonrealism in the EPR thought experiment and Bell tests?
  • "There is a bra for every ket, but there is not a ket for every bra"
  • Function with memories of its past life
  • The meaning of an implication in an existential quantifier
  • Does a Malaysian citizen require a Canadian visa to go on an Alaskan cruise
  • How to NDSolve stiff ODE?
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • Is it defamatory to publish nonsense under somebody else's name?
  • Is it true that before European modernity, there were no "nations"?
  • Strange behavior of Polygon with a hole
  • Is a thing just a class with only one member?
  • Multi-producer, multi-consumer blocking queue
  • 1950s comic book about bowling ball looking creatures that inhabit the underground of Earth
  • How can I switch from MAG to TRU heading in a 737?
  • Is it possible to draw this picture without lifting the pen? (I actually want to hang string lights this way in a gazebo without doubling up)
  • How many engineers/scientists believed that human flight was imminent as of the late 19th/early 20th century?
  • Why was Esther included in the canon?
  • Why is the \[ThickSpace] character defined as 5/18 em instead of 1/4 em as in Unicode?
  • How can I analyze the anatomy of a humanoid species to create sounds for their language?
  • Does SpaceX Starship have significant methane emissions?
  • Is it a correct rendering of Acts 1,24 when the New World Translation puts in „Jehovah“ instead of Lord?
  • What's the difference between "Erase All Content and Settings" and using the Disk Utility to erase a Mac with Apple silicon
  • What would be an appropriate translation of Solitude?
  • On the history of algae classification

right assignment in r

IMAGES

  1. Assignment Operators in R

    right assignment in r

  2. Assignment Operators in R (3 Examples)

    right assignment in r

  3. R Operators

    right assignment in r

  4. How to use the double assignment operator in R

    right assignment in r

  5. 4

    right assignment in r

  6. How to Find Your Right Assignment Expert : r/expertassignment

    right assignment in r

VIDEO

  1. BSSS 183 solved assignment 2024-25 in English || bsss 183 solved assignment 2025 || bsss183 2024-25

  2. You can apply now for an Assignment Writing Job from Home. No investment required JustRemote

  3. Java Operators Explained…Comprehensive Guide and Examples in tamil PART 2

  4. Master SAP Service Purchase Orders (ME21N) Like a Pro!

  5. Assignment r bhalo lage na🥲 #shorts #vlog

  6. Assignment Model in R-Studio

COMMENTS

  1. Why are there two assignment operators, `<-` and `->` in R?

    I can't speculate on R's reasons for allowing left-to-right assignment. And it's certainly true that most programming languages (nearly all, in fact) perform only right-to-left assignment.

  2. How exactly does R parse `->`, the right-assignment operator?

    So this is kind of a trivial question, but it's bugging me that I can't answer it, and perhaps the answer will teach me some more details about how R works. The title says it all: how does R parse...

  3. Assignment Operators in R (3 Examples)

    How to use different assignment operators in R - 3 R programming examples - Difference of = vs. <- vs. <<- R tutorial & syntax in RStudio

  4. R: Assignment Operators

    In all the assignment operator expressions, x can be a name or an expression defining a part of an object to be replaced (e.g., z[[1]]). A syntactic name does not need to be quoted, though it can be (preferably by backtick s). The leftwards forms of assignment <- = <<- group right to left, the other from left to right.

  5. Assignment Operators in R

    The R programming language has several different assignment operators. Let's take a look at the some differences between and when suggestions to use them.

  6. assignOps: Assignment Operators

    There are three different assignment operators: two of them have leftwards and rightwards forms. 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 ...

  7. Assignment Operators in R

    For Assignments. The <- operator is the preferred choice for assigning values to variables in R. It clearly distinguishes assignment from argument specification in function calls. # Correct usage of <- for assignment x <- 10 # Correct usage of <- for assignment in a list and the = # operator for specifying named arguments my_list <- list (a = 1 ...

  8. R: Assignment Operators

    In all the assignment operator expressions, x can be a name or an expression defining a part of an object to be replaced (e.g., z [ [1]] ). The name does not need to be quoted, though it can be. The leftwards forms of assignment <- = <<- group right to left, the other from left to right.

  9. Difference between assignment operators in R

    For R beginners, the first operator they use is probably the assignment operator<-. Google's R Style Guide suggests the usage of <- rather than = even though the equal sign is also allowed in R to do exactly the same thing when we assign a value to a variable. However, you might feel inconvenient because you need to type two characters to represent one symbol, which is different from many ...

  10. R: Assignment operators

    Assignment operators Description. Modifies the stored value of the left-hand-side object by the right-hand-side object. Equivalent of operators such as +=-= *= /= in languages like c++ or python.%+=% and %-=% can also work with strings. Usage

  11. R Operators [Arithmetic, Logical, ... With Examples]

    R operators. There are several operators in R, such that arithmetic operators for math calculations, logical, relational or assignment operators or even the popular pipe operator. In this tutorial we will show you the R operators divided into operator types. In addition, we will show examples of use of every operator.

  12. R right assignment operator example

    R - right assignment operator example Right Assignment operator assigns value of right hand side expression to right hand side operand. R has two such kind of operators (-> and ->>).

  13. A Step to the Right in R Assignments

    Anyone using R knows that the two most common methods of assignment are the venerable (and sensible) left arrow <- and it's lesser cousin =. <- has an evil sibling, <<-, which is used when you want/need to have R search through parent environments for an existing definition of the variable being assigned (up to the global environment).

  14. Why do we use arrow as an assignment operator?

    It was removed in R 1.8: (So no, at that time, no snake_case_naming_convention) Colin Gillespie published some of his code from early 2000, where assignment was made like this 🙂. The main reason "equal assignment" was introduced is because other languages uses = as an assignment method, and because it increased compatibility with S-Plus.

  15. The Case For Using -> In R

    The R -style guides routinely insist on " <- " as being the only preferred form. In this note we are going to try to make the case for " -> " when using magrittr pipelines. [edit: After reading this article, please be sure to read Konrad Rudolph's masterful argument for using only " = " for assignment. He also demonstrates a function to land values from pipelines (though that is ...

  16. Logical, Comparision, Assignment and Arithmetic Operators in R

    In R, operators allow you to perform various tasks, from basic arithmetic operations to data manipulation and comparison tasks. There are different kinds of operators in R, which include arithmetic, logical, assignment, and comparison operators etc.

  17. R

    Assignment operators R uses the following assignment operators: <- assigns a value to a variable from right to left. -> assigns a value to a variable left to right. <<- is a global version of <-. ->> is a global version of ->. = works the same way as <-, but its use is discouraged.

  18. R Operators (With Examples)

    R has many operators to carry out different mathematical and logical operations. Operators perform tasks including arithmetic, logical and bitwise operations.

  19. A Step to the Right in R Assignments

    Anyone using R knows that the two most common methods of assignment are the venerable (and sensible) left arrow `<-` and it's lesser cousin `=`. `<-` has an evil sibling, `<<-`, which is used when you want/need to have R search through parent environments for an existing definition of the variable being assigned (up to the global environment ...

  20. What is the difference between assign () and <<- in R?

    Learn the difference between assign () and <<- in R, two ways of assigning values to variables in the global environment, with examples and explanations.

  21. How do you use "<<-" (scoping assignment) in R?

    Instead, it seems that R looks outside of the fortest function, can't find a mySum variable to assign to, so creates one and assigns the value 1, the first time through the loop. On subsequent iterations, the RHS in the assignment must be referring to the (unchanged) inner mySum variable whereas the LHS refers to the global variable.