Open In App

Convert Character String to Variable Name in R

Improve
Improve
Like Article
Like
Save
Share
Report

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

the time complexity of creating five variables using assign() and printing the variable name using print() is O(1) + O(1) = O(1).

The auxiliary space complexity of creating the variables using assign() is O(n)

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 


Last Updated : 03 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads