Rename Columns of a Data Frame in R Programming – rename() Function
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
df <- library (plyr)
df<- data.frame (row1 = 0:2, row2 = 3:5, row3 = 6:8)
print ( "Original Data Frame" )
print (df)
print ( "Modified 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
df <- library (plyr)
df = data.frame (
"col1" = c ( "abc" , "def" , "ghi" ),
"col2" = c ( "R" , "Python" , "Java" ),
"col3" = c (22, 25, 45)
)
df
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
data (iris)
head (iris)
rename_columns<- rename (iris, c ( 'Sepal.Length' = 'iris1' , 'Sepal.Width' = 'iris2' ,
'Petal.Length' = 'iris3' , 'Petal.Width' = 'iris4' ))
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.
Last Updated :
20 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...