A data frame is a tabular structure with fixed dimensions, of each rows as well as columns. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.
colnames() method: colnames() method in R is used to rename and replace the column names of the data frame in R.
Syntax:
colnames(df) <- c(new_col1_name,new_col2_name,new_col3_name)
Example:
# declaring the columns of data frame
df = data.frame(
col1 = c('A', 'B', 'C', 'J', 'E', NA,'M'),
col2 = c(12.5, 9, 16.5, NA, 9, 20, 14.5),
col3 = c(NA, 3, 2, NA, 1, NA, 0))
# printing original data frame
print("Original data frame : ")
print(df)
print("Renaming columns names ")
# assigning new names to the columns of the data frame
colnames(df) <- c('C1','C2','C3')
# printing new data frame
print("New data frame : ")
print(df)
Output:
[1] “Original data frame : “
col1 col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 J NA NA
5 E 9.0 1
6 <NA> 20.0 NA
7 M 14.5 0
[1] “Renaming columns names “
[1] “New data frame : “
C1 C2 C3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 J NA NA
5 E 9.0 1
6 <NA> 20.0 NA
7 M 14.5 0
setNames() method: setNames() method in R can also be used to assign new names to the columns contained within a list, vector or tuple.
Syntax:
setnames(df, c(names of new columns))
Example:
# declaring the columns of data frame
df = data.frame(
col1 = c('A', 'B', 'C', NA,'M'),
col2 = c(12.5, 9, 16.5, 20, 14.5),
col3 = c(NA, 3, 2, NA, 0))
# printing original data frame
print("Original data frame : ")
print(df)
# print("Renaming columns names ")
# renaming all the column names of data frame
df <- setNames(df, c("changed_Col1","changed_Col2","changed_Col3"))
print("Renamed data frame : ")
print(df)
Output:
[1] “Original data frame : “
col1 col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 <NA> 20.0 NA
5 M 14.5 0
[1] “Renamed data frame : “
changed_Col1 changed_Col2 changed_Col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 <NA> 20.0 NA
5 M 14.5 0