Create Variable Name Using paste() Function in R (Example)
In this tutorial you’ll learn how to create a new variable using the paste() function in the R programming language.
The table of content is structured as follows:
With that, let’s take a look at some R codes in action!
Example: Create Variable Name with paste0() & assign() Functions
This Example explains how to apply the paste0 and assign functions to define a new variable in R.
assign(paste0("variable_", 1), 1:5) # Using assign function
Let’s have a look at the output:
variable_1 # Return new variable to console # 1 2 3 4 5
As you can see based on the previous output of the RStudio console, we have created a new vector object called variable_1.
Video, Further Resources & Summary
Would you like to learn more about pasting variable names? Then you could watch the following video of my YouTube channel. In the video, I illustrate the R programming syntax of this tutorial.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you could read the related posts of this homepage. I have published several tutorials already.
- Get Column Index in Data Frame by Variable Name
- Convert Character String to Variable Name
- Useful Functions in R
- R Programming Examples
Summary: At this point you should have learned how to apply the paste function to create a new variable name in R. Please let me know in the comments, in case you have further questions.
Statistics Globe Newsletter
4 Comments. Leave new
Thanks Joachim but I can’t follow what “assign” and “paste0” are doing.
To me its just a magic box that spits out a reply.
Hi Jeff,
Please have a look at the following two tutorials. They explain those two functions in some more detail:
https://statisticsglobe.com/assign-function-in-r
https://statisticsglobe.com/r-paste-paste0-function-example
Regards,
Joachim
Hi Joachim,
I’ve created a series of data frames based off of 2 sets of 3 different parameters for a monte carlo simulation i.e. rho = (1,2,3) variance = (4,5,6). I’ve dynamically named my 9 different dataframes using a double for loop and assign(paste()). I’m having trouble appending the dataframes outside my loop. I can see that they exist in my global environment, and can call them in the console whether they appear with a ` on either side, however I can’t seem to rbind them, for example, rbind(paste(“df”,rho, variance, sep=””) to bring them back into one dataframe. I’ve read around and it looks like assign creates this problem. Any advice?
Hey Steven,
Please excuse the delayed response. I was on a long holiday, so unfortunately I wasn’t able to reply sooner. Still need help with your code?
Regards,
Joachim