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 data frame add prefix column names r

 

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

In this example, I’ll show how to rename the column names of our data frame by adding a prefix in front of the column names.

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

 

table 2 data frame add prefix column names r

 

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:

 

The YouTube video will be added soon.

 

In addition, you might read the related tutorials on my website.

 

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.

 

Subscribe to my free statistics 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.

Menu
Top