In this tutorial, we will learn how to change column name of R Data frame.

Column names of an R Data frame can be acessed using the function colnames(). You can also access the individual column names using an index to the output of colnames() just like an array.

To change all the column names of an R Data frame, use colnames() as shown in the following syntax

colnames(mydataframe) = vector_with_new_names

To change a single column name of an R Data frame, use colnames() with index as shown in the following syntax

colnames(mydataframe)[index] = new_name

Example 1 – Change a Column Name of Data Frame

In this example, we will create an R data frame DF1 and change the second column’s name to “newC”.

> DF1 = data.frame(C1= c(1, 5, 14, 23, 54), C2= c(9, 15, 85, 3, 42), C3= c(9, 7, 42, 87, 16))
> DF1
  C1 C2 C3
1  1  9  9
2  5 15  7
3 14 85 42
4 23  3 87
5 54 42 16
> colnames(DF1)[2] = "newC"
> DF1
  C1 newC C3
1  1    9  9
2  5   15  7
3 14   85 42
4 23    3 87
5 54   42 16
>

The column name C2 has changed to newC.

Example 2 – Change All Column Names of Data Frame

In this example, we will create an R data frame DF1 and change all the column’s names.

> DF1 = data.frame(C1= c(1, 5, 14, 23, 54), C2= c(9, 15, 85, 3, 42), C3= c(9, 7, 42, 87, 16))
> DF1
  C1 C2 C3
1  1  9  9
2  5 15  7
3 14 85 42
4 23  3 87
5 54 42 16
> colnames(DF1) = c("newC1", "newC2", "newC3")
> DF1
  newC1 newC2 newC3
1     1     9     9
2     5    15     7
3    14    85    42
4    23     3    87
5    54    42    16
>

All the column names have been changed.

Conclusion

In this R Tutorial, we have learnt how to change column name of R Data frame.