Assignment operators
   get_help() docs


Description

We define new variables in R using an assignment operator: One of -> or <-, which look like arrows and are comprised of a minus sign and either a greater or less than symbol. Assignment is always directed from the value TOWARDS the variable.

Although your code will still likely work if you use = to assign values to variables, this is not the preferred style and may incur certain risks.

When we are working to assign aspects of a variable (i.e. create a new column in a data frame or tibble), we use =.


Conceptual Usage

# Point the arrow FROM the value TO the variable
variable_name <- value to assign to variable_name

value to assign to variable_name -> variable_name

Examples

# Define the variable x with the value 12, and show the value of x
x <- 12
x
## [1] 12


# Define the variable x with the value 12, and show the value of x
12 -> x
x
## [1] 12


# This will result in an error because the assignment operator is pointing backwards!
12 <- x
## Error in 12 <- x: invalid (do_set) left-hand side to assignment


# We use `<-` to create the data frame variable, but `=` to define aspects internal to a variable
my_new_data_frame <- data.frame(
  first_column  = c(1,2),
  second_column = c("A", "B")
)
my_new_data_frame
##   first_column second_column
## 1            1             A
## 2            2             B