You can use the following methods to add a suffix to column names in R:
Method 1: Add Suffix to All Column Names
colnames(df) my_suffix', sep = '_')
Method 2: Add Suffix to Specific Column Names
colnames(df)[c(1, 3)] my_suffix', 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
Example 1: Add Suffix to All Column Names
The following code shows how to add the suffix ‘_total‘ to all column names:
#add suffix '_total' to all column names
colnames(df) total', sep = '_')
#view updated data frame
df
points_total assists_total rebounds_total
1 99 33 30
2 90 28 28
3 86 31 24
4 88 39 24
5 95 34 28
Notice that the suffix ‘_total‘ has been appended to the end of each column name.
Example 2: Add Suffix to Specific Column Names
The following code shows how to add the suffix ‘_total‘ to specific column names:
#add suffix '_total' to column names in index positions 1 and 3
colnames(df)[c(1, 3)] total', sep = '_')
#view updated data frame
df
points_total assists rebounds_total
1 99 33 30
2 90 28 28
3 86 31 24
4 88 39 24
5 95 34 28
Notice that the suffix ‘_total‘ has only been appended 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