How to Change Columns Names in R

There are two ways to change column names in R, one is to change all column names and a specific column name. The following is the R code syntax to change column names.

Method 1: Change a specific column name:

colnames(df_name)[which(names(df_name) == ‘old_col_name’)] <- ‘new_col_name’

Method 2: Change all column names:

colnames(dataframe_name) <- c(“New_col_name_1″,”New_col_name_2”,…)

Example for Method 1: Change a specific column name in R

Example 1 shows how to change a specific column name in R.

# create a data frame  
df <- data.frame (cities  = rep(c('City1','City2'),each=5),
                  stores = rep(c('store1','store2'), 5),
                  sales=c(10,20,20,50,30,10,5,4,12,4))

# print out the data frame with original names
print(df)

# R code to change a specific column name: 
colnames(df)[which(names(df) == 'cities')] <- 'CITY'

# print out the DataFrame with a new name  
print(df)
> print(df)
   cities stores sales
1   City1 store1    10
2   City1 store2    20
3   City1 store1    20
4   City1 store2    50
5   City1 store1    30
6   City2 store2    10
7   City2 store1     5
8   City2 store2     4
9   City2 store1    12
10  City2 store2     4

> print(df)
    CITY stores sales
1  City1 store1    10
2  City1 store2    20
3  City1 store1    20
4  City1 store2    50
5  City1 store1    30
6  City2 store2    10
7  City2 store1     5
8  City2 store2     4
9  City2 store1    12
10 City2 store2     4

Example for method 2: Change all column names in R

We can also change all column names in R via the following R code.

# create a data frame  
df <- data.frame (cities  = rep(c('City1','City2'),each=5),
                  stores = rep(c('store1','store2'), 5),
                  sales=c(10,20,20,50,30,10,5,4,12,4))

# print out the data frame with original names
print(df)

# R code to change all column names: 
colnames(df) <- c("CITY","STORE","SALES")

# print out the DataFrame with new names  
print(df)
> print(df)
   cities stores sales
1   City1 store1    10
2   City1 store2    20
3   City1 store1    20
4   City1 store2    50
5   City1 store1    30
6   City2 store2    10
7   City2 store1     5
8   City2 store2     4
9   City2 store1    12
10  City2 store2     4

> print(df)
    CITY  STORE SALES
1  City1 store1    10
2  City1 store2    20
3  City1 store1    20
4  City1 store2    50
5  City1 store1    30
6  City2 store2    10
7  City2 store1     5
8  City2 store2     4
9  City2 store1    12
10 City2 store2     4

Further Reading