R Data Frame – Rename Columns

Column names of an R Data frame can be accessed using the function colnames(). We can also access the individual column names using an index to the output of colnames() just like an array with notation colnames(df)[index].

To rename columns of an R Data Frame, assign colnames(dataframe) with the required vector of column names. To change a single column name, we may use index notation.

Syntax

The syntax to rename all the column of an R Data Frame df using colnames() is

</>
Copy
 colnames(df) <- new_names

where new_names is a vector of new column names.

The syntax to rename single column of an R Data Frame df using colnames() with index is

</>
Copy
 colnames(df)[index] <- new_name

where new_name is the new column name for column in position given by index.

Examples

In this example, we create an R data frame df and set the column names with the vector c("p", "q", "r").

example.R

</>
Copy
df <- data.frame(a = c(41, 42, 43, 44),
                 b = c(45, 46, 47, 48),
                 c = c(49, 50, 51, 52))

print("Original Data Frame")
print(df)

colnames(df) <- c("p", "q", "r")
print("After changing column names")
print(df)

Output

[1] "Original Data Frame"
   a  b  c
1 41 45 49
2 42 46 50
3 43 47 51
4 44 48 52
[1] "After changing column names"
   p  q  r
1 41 45 49
2 42 46 50
3 43 47 51
4 44 48 52

The column names of the Data Frame changed to the new values.

Now, let us change the column name of column with index = 2 to "w".

example.R

</>
Copy
df <- data.frame(a = c(41, 42, 43, 44),
                 b = c(45, 46, 47, 48),
                 c = c(49, 50, 51, 52))

print("Original Data Frame")
print(df)

colnames(df)[2] <- "w"
print("After changing column name")
print(df)

Output

[1] "Original Data Frame"
   a  b  c
1 41 45 49
2 42 46 50
3 43 47 51
4 44 48 52
[1] "After changing column name"
   a  w  c
1 41 45 49
2 42 46 50
3 43 47 51
4 44 48 52

Conclusion

In this R Tutorial, we learned to rename columns of R Data Frame using colnames(dataframe), with the help of examples.