Rename Columns in R

How to Rename Columns in R

This page will show you how to rename columns in R with examples using either the existing column name or the column number to specify which column name to change.

Warning: R will allow a field to be named with a space but you won’t be able to easily refer to that column after the name change. If you need to make column names more readable for presentation do this as a final step just before exporting the data from R.

Example 1

The first example shows how to change the names of the columns in a data frame.  This starts with the first column and goes until it runs out of the names you’ve provided. For example, if there are eight columns in your data frame but you only provide two names only the first two columns will be renamed.

names(data) <- c("new_name", "another_new_name")

Example 2

The second example shows how to change the name of a column using the name to identify which column to apply the name to. The following code will rename the field old_name to new_name in the data frame called data.

# Rename a column in R
colnames(data)[colnames(data)=="old_name"] <- "new_name"

Example 3

The third example shows how to again change the name of a column using the column name to identify which column to apply the name to. The advantage of this method is that it can rename more than one field at a time. One disadvantage is that its possible to get the field names out of order in the “old” and “new” commands resulting in columns that are named incorrectly. The other disadvantage is that it requires the data.table package.

library(data.table)
setnames(data, old=c("old_name","another_old_name"), new=c("new_name", "another_new_name"))

Example 4

The fourth example shows how to change the name of a column using the column number to identify which column to apply the name to. The following code will rename third column in the data frame data to the name new_name. I try to avoid using this method because if the order of the columns changes it will change the name of the wrong column.

# Rename a column in R
names(data)[3]<-"new_name"

See official R-manual page on colnames to learn more: http://stat.ethz.ch/R-manual/R-patched/library/base/html/colnames.html.

Thanks for reading! This website took a great deal of time to create. If it was helpful to you, please show it by sharing with friends, liking, or tweeting! If you have any thoughts regarding this R code please post in the comments.

JM

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>