Skip to content
Related Articles

Related Articles

Improve Article

Convert Character String to Variable Name in R

  • Last Updated : 09 May, 2021
Geek Week

In this article we will discuss how to convert a character string to the variable name in the R programming language i.e. we are going to assign the character string to the variable as the variable name

Method 1: Using assign() function

We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function.

Syntax: assign(“variable_name”,value)

Parameter:

  • variable_name is the name of the value
  • value is the variable.

Example:



R




# assign variable name to 3 value
assign("variable_name",3)
  
# print variable name
print(variable_name)

Output:

[1] 3

We can also create a vector with a group of variables and assign a single variable name.

Example:

R




# create 5 variables at a time
assign("vector1",c(1,2,3,4,5))
  
# print variable name
print(vector1)

Output:

[1] 1 2 3 4 5

Method 2: Using do.call() function

This function allows you to call any R function. It allows using a list to hold the arguments of the function along with passing of single arguments.

Syntax:



do.call(“=”,list(“variable_name”, value))

Where “=” is an assign operator

The variable name is the named assigned to the value and value is the input value/variable.

Example:

R




do.call("=",list("a", 1))
  
print(a)

Output:

[1] 1

Example:

R




do.call("=",list("a", c(1,2,3,4,5)))
  
print(a)

Output:

[1] 1 2 3 4 5 



My Personal Notes arrow_drop_up
Recommended Articles
Page :