Table of Contents
To add a prefix to column names in R, you can use the paste() function or the colnames() function combined with the for loop. The paste() function allows you to specify a prefix to be added to the existing column name, while the colnames() function can be used to assign new names to the columns in a data frame. Both of these functions can be used to quickly add a prefix to all the column names in a data frame.
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) <- paste('my_prefix', colnames(df), sep = '_')
Method 2: Add Prefix to Specific Column Names
colnames(df)[c(1, 3)] <- paste('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 <- data.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:
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) <- paste('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)] <- paste('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.