# assign Function in R (2 Examples)

In this tutorial, I’ll illustrate how to assign values to a variable name using the assign() function in R.

Sound good? Great, here’s how to do it…

## Definition & Basic R Syntax of assign Function

Definition: The assign R function assigns values to a variable name.

Basic R Syntax: Please find the basic R programming syntax of the assign function below.

`assign("variable_name", values) # Basic R syntax of assign function`

In the remaining article, I’ll show you two examples for the application of the assign function in the R programming language.

## Example 1: Using assign Function to Create New Vector

In Example 1, I’ll show how to use the assign() command to assign numeric values to a new vector object.

Within the assign function, we have to specify the name of the new vector (i.e. “x”) and the values we want to store in this vector object (i.e. five numeric values ranging from 1 to 5):

`assign("x", 1:5) # Applying assign function`

Let’s have a look at our new data object x:

```x # Returning output # 1 2 3 4 5```

As you can see based on the previous output of the RStudio console, we have saved a numeric sequence from 1 to 5 in a new variable called x.

## Example 2: Using assign & paste0 Functions Dynamically in for-Loop

In Example 2, I’ll show how to use the assign function in combination with the paste0 function to create new variable names within a for-loop dynamically.

Within the assign function, we are using paste0 to create new variable names combining the prefix “x_” with the running index i:

```for(i in 1:3) { # Head of for-loop assign(paste0("x_", i), i) # Combining assign & paste0 }```

Let’s have a look at the output variables:

```x_1 # First variable # 1 x_2 # Second variable # 2 x_3 # Third variable # 3```

## Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. I explain the contents of this article in the video:

In addition, you might have a look at the related tutorials on this homepage.

In this R tutorial you learned how to create new data objects using assign(). In case you have further questions, let me know in the comments section.

Subscribe to the Statistics Globe Newsletter

• 