How to Use the assign() Function in R (3 Examples)


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 for loop 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

By using the assign() function with a for loop, we were able to create four new variables.

Additional Resources

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

How to Use the dim() Function in R
How to Use the table() Function in R
How to Use sign() Function in R

Leave a Reply

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