How to use the assign() function in R (3 Examples)

The assign() function in R is used to assign a value to an object. The syntax for this is assign(x, value). The x argument is the name of the object, and the value argument is the value to assign to the object. Examples include assigning a value to an existing object, assigning a value to a new object, and assigning a list to an object.


The assign() function in R can be used to assign values to variables.

This function uses the following basic syntax:

assign(x, value)

where:

  • x: A variable name, given as a character string.
  • value: The value(s) to be assigned to x.

The following examples show how to use this function in practice.

Example 1: Assign One Value to One Variable

The following code shows how to use the assign() function to assign the value of 5 to a variable called new_variable:

#assign one value to new_variable
assign('new_variable', 5)

#print new_variable
new_variable

[1] 5

When we print the variable called new_variable, we can see that a value of 5 appears.

Example 2: Assign Vector of Values to One Variable

The following code shows how to use the assign() function to assign a vector of values to a variable called new_variable:

#assign vector of values to new_variable
assign('new_variable', c(5, 6, 10, 12))

#print new_variable
new_variable

[1]  5  6 10 12

When we print the variable called new_variable, we can see that a vector of values appears.

Example 3: Assign Values to Several Variables

The following code shows how to use the assign() function within a to assign specific values to several new variables:

#use for loop to assign values to different variables
for(i in 1:4) {
  assign(paste0("var_", i), i*2)
}

#view variables created in for loop
var_1

[1] 2

var_2

[1] 4

var_3

[1] 6

var_4

[1] 8

The following tutorials explain how to use other common functions in R:

x