Home » How to Add Prefix to Column Names in R (With Examples)

How to Add Prefix to Column Names in R (With Examples)

by Tutor Aspire

You can use the following methods to add a prefix to column names in R:

Method 1: Add Prefix to All Column Names

colnames(df) my_prefix', colnames(df), sep = '_')

Method 2: Add Prefix to Specific Column Names

colnames(df)[c(1, 3)] my_prefix', colnames(df)[c(1, 3)], sep = '_')

The following examples show how to use each method with the following data frame:

#create data frame
df frame(points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))	

#view data frame
df

  points assists rebounds
1     99      33       30
2     90      28       28
3     86      31       24
4     88      39       24
5     95      34       28

Related: How to Add Suffix to Column Names in R

Example 1: Add Prefix to All Column Names

The following code shows how to add the prefix ‘total_‘ to all column names:

#add prefix 'total_' to all column names
colnames(df) total', colnames(df), sep = '_') 

#view updated data frame
df

  total_points total_assists total_rebounds
1           99            33             30
2           90            28             28
3           86            31             24
4           88            39             24
5           95            34             28

Notice that the prefix ‘total_‘ has been added to each column name.

Example 2: Add Prefix to Specific Column Names

The following code shows how to add the prefix ‘total_‘ to specific column names:

#add prefix 'total_' to column names in index positions 1 and 3
colnames(df)[c(1, 3)] total', colnames(df)[c(1, 3)], sep = '_') 

#view updated data frame
df

  total_points assists total_rebounds
1           99      33             30
2           90      28             28
3           86      31             24
4           88      39             24
5           95      34             28

Notice that the prefix ‘total_‘ has only been added to the columns in index positions 1 and 3.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Loop Through Column Names in R
How to Rename a Single Column in R
How to Check if Column Exists in Data Frame in R

You may also like