The assign() function is used to assign value to variable in R.
The following method in R shows how you can do it with syntax.
Method: Use assign() Function
assign(variable,value)
The following examples shows how to use assign() function in R.
Use assign() Function to Single Variable
Let’s see how we can use assign value to variable using assign() function:
# Assign value to variable
assign("var1",52)
# Show variable
print(var1)
Output:
[1] 52
The output shows value 52 assign to var1 variable.
Use assign() Function to Vector
Using assign() function you can assign values to vector:
# Assign vector of values to variable
assign("vect1",c(12,14,45,85,"A","u"))
# Print variable
print(vect1)
Output:
[1] "12" "14" "45" "85" "A" "u"
Here the output shows values assign to vect1 variable.
Use assign() Function to Multiple Variable
You can use assign() function to assign values to multiple variables:
# Use for loop to assign values to several variables
for(i in 1:5){
assign(paste0("var",i),i)
}
# Show variable
print(var1)
print(var2)
print(var3)
print(var4)
print(var5)
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
As we can see using assign() function with for loop we assing values to five variables.