How to Change Column Name of Data Frame in R

Sometimes we need to change column name of a specific data frame in R. We can do this by different ways in R. Here I will show four methods of doing this.

This method is very much simple. Serially it will change the column name from first. The following code will change the first two columns as “customer_id” and “customer_name” in the data frame “ds_churn_1000”. If you want to change all column names or want to change first few column names then you can use this method. Generally I try to avoid using this method.

names(ds_churn_1000) <- c("customer_id", "customer_name")

In this method we will change column name by it’s column index. The following code will change second column in the data frame “ds_churn_100” to the name “customer_name”. Generally I try to avoid using this method because if the order of the columns changes it will change the name of the unwanted column.


In this method we will identify targeted column by it’s column name and then change the existing name by new one. The following code will change the old column name “cn” with the new one “customer_name” in the data frame “ds_churn_1000”. Generally I feel comfort to use the below method when I need to change only one column and I’ll suggest you to follow this method.

colnames(ds_churn_1000)[colnames(ds_churn_1000)=="cn"] <- "customer_name"

This method is also a good method. In this method you have to create an array of old column names as well as array of new column  names. The main advantage of this method is you can change multiple columns at a time. The following code will change columns “id” to “customer_id” and “cn” to “customer_name” in the data frame “ds_churn_1000” . In this method targeted column is identified by it’s old column name. On the other hand main disadvantage of this method is that it requires the data.table package.  If you need to change many columns, I’ll suggest you to use this method.


setnames(ds_churn_1000, old=c("id","cn"), new=c("customer_id", "customer_name"))

Very soon we will incorporate video to make you understand clearly. Just keep in touch at our facebook page


[poll id=”2″]

Add a Comment