Convert Character String to Variable Name in R (2 Examples)

 

In this article you’ll learn how to use a character string as variable name in the R programming language.

The article will consist of the following topics:

Let’s dive right in!

 

Example 1: Convert String to Variable Name with assign Function

Example 1 shows how to turn a character string to a variable name using the assign function. Have a look at the following R code:

assign("my_string_1", 1:5)                   # Apply assign function

Within the assign function, we defined our character string (i.e. “my_string_1”) as well as the values we want to store in the new variable (i.e. a numeric range from 1 to 5). Let’s have a look at the new data object my_string_1:

my_string_1                                  # Return variable values
# 1 2 3 4 5

As expected: The variable my_string_1 contains the numeric range 1 to 5.

 

Example 2: Convert String to Variable Name with do.call Function

In Example 2, I’ll show an alternative R syntax, which is based on the do.call function:

do.call("<-", list("my_string_2", 1:5))      # Apply do.call function

Within the do.call function, we had to specify the operation we want to call (i.e. “<-") and we had to create a list consisting of our character string / variable name and the values we want to assign. Let's have a look at the output in the RStudio console:

my_string_2                                  # Return variable values
# 1 2 3 4 5

The result is exactly the same as in Example 1.

 

Video & Further Resources

In case you need further information on the content of this tutorial, you might have a look at the following video of my YouTube channel. In the video instruction, I show the R codes of this page:

 

 

Furthermore, you could have a look at the related articles of my website:

 

To summarize: In this tutorial you learned how to get strings recognized as variable names in R. In case you have any additional questions and/or comments, let me know in the comments section below. Furthermore, don’t forget to subscribe to my email newsletter for updates on new tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top