7.7 C
London
Sunday, March 9, 2025
HomeRDescriptive Statistics in RHow to Use the assign() Function in R (3 Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories