Add Prefix to Column Names in R (Example)
In this R programming article you’ll learn how to insert a prefix in front of the column names of a data frame.
Table of contents:
Let’s dive right into the example!
Creation of Example Data
We use the following data as basement for this R programming tutorial:
data <- data.frame(x1 = letters[8:5], # Create example data x2 = 4:7, x3 = 4) data # Print example data
Table 1 shows the structure of our example data: It consists of four rows and three columns. The variables of our data frame are called x1, x2, and x3.
Example: Add Prefix to Variable Names Using colnames() & paste0() Functions
Have a look at the following R syntax:
data_new <- data # Duplicate data colnames(data_new) <- paste0("foo_", colnames(data_new)) # Add prefix data_new # Print updated data
The output of the previous R syntax is shown in Table 2: A data frame with prefixes in front of the column names.
Note that we could use a similar R code to add a suffix to the end of our column names as well. We would just have to change the ordering within the paste0 function.
Video, Further Resources & Summary
Have a look at the following video of my YouTube channel. In the video, I’m showing the R programming codes of this article:
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 might read the related tutorials on my website.
- Convert Values in Column into Row Names of Data Frame
- Add New Column to Data Frame in R in R
- Merge Data Frames by Column Names
- Specify Column Names for X & Y when Joining with dplyr Package
- All R Programming Examples
To summarize: In this article, I have explained how to add an affix in front of all column names in the R programming language. Please tell me about it in the comments section, if you have further questions. Furthermore, don’t forget to subscribe to my email newsletter to receive updates on new articles.