Rename Columns of a Data Frame in R Programming – rename() Function
Last Updated :
20 Dec, 2023
Improve
In this article, we will discuss how to Rename the Columns of a Data Frame in R Programming Language using the rename() Function.
rename function in R
rename()
function in R Programming Language is used to rename the column names of a data frame, based on the older names.
Syntax:
rename(x, names)
Parameters:
x: Data frame
names: Old name and new name
Rename a Data Frame using rename function in R
R
# R program to rename a Data Frame # Adding Package df <- library (plyr) # Creating a Data Frame df<- data.frame (row1 = 0:2, row2 = 3:5, row3 = 6:8) print ( "Original Data Frame" ) print (df) print ( "Modified Data Frame" ) # Renaming Data Frame rename (df, c ( "row1" = "one" , "row2" = "two" , "row3" = "three" )) |
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
one two three
1 0 3 6
2 1 4 7
3 2 5 8
Modify names of a data frame using rename function in R
R
# R program to modify names of a data frame # Loading library df <- library (plyr) # Creating a data frame df = data.frame ( "col1" = c ( "abc" , "def" , "ghi" ), "col2" = c ( "R" , "Python" , "Java" ), "col3" = c (22, 25, 45) ) df # Calling rename() function rename (df, c ( "col1" = "Name" , "col2" = "Language" , "col3" = "Age" )) |
Output:
col1 col2 col3
1 abc R 22
2 def Python 25
3 ghi Java 45
Name Language Age
1 abc R 22
2 def Python 25
3 ghi Java 45
Change Multiple Columns using rename function in R
R
#load iris dataset data (iris) # print top records of the dataset head (iris) # rename the column names rename_columns<- rename (iris, c ( 'Sepal.Length' = 'iris1' , 'Sepal.Width' = 'iris2' , 'Petal.Length' = 'iris3' , 'Petal.Width' = 'iris4' )) # Print renames columns names head (rename_columns)A |
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
iris1 iris2 iris3 iris4 Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
rename function in R examples provided a practical approach to manage column names in a way that facilitates data analysis and interpretation. Whether we are dealing with an existing dataset or creating a new one, thoughtful column naming is essential for maintaining code readability and ensuring that your data is effectively communicated.