To Set the Row names
In Data frame’s rows can be accessed by using the functions, such as rownames() ,row.names()..etc. By default, every row name or indexes starts from from 1 and should be unique.Set the row names mean removing default names and adding new names. For setting row names , we using some methods are.
- rownames()
- row.names()
Setting the row names using rownames()
rownames() is used for accessing row names in a data frame. By default, every row names or indexes starts from 1. The function ‘rownames()’ can have ability to set or add new names which were present in the dataframe.
Syntax
rownames(DataFrame)
Here, created a dataframe by using different vectors. After, by accessing a vector to the function ‘rownames(df)’ ,we changed the row names.
R
#vector1 a= c ( "ck" , "dm" , "cd" ) #vector2 b= c (1,2,3) #vector3 c= c ( "kk" , "ll" , "mm" ) print ( "original dataframe:" ) # creating dataframe df= data.frame (a,b,c) print (df) #changing the row names rownames (df)= c ( "A" , "B" , "C" ) print ( "After Modifying the dataframe:" ) print (df) |
Output:
[1] "original dataframe:"
a b c
1 ck 1 kk
2 dm 2 ll
3 cd 3 mm
[1] "After Modifying the dataframe:"
a b c
A ck 1 kk
B dm 2 ll
C cd 3 mm
Setting the row names using row.names()
row.names() function can have ability to set or add new row names for the dataframes and works much similar to function ‘rownames()’ . The ‘row.names()’ is used for accessing the rows in efficient manner. By default row names or indexes starts from 1.
row.names(Dataframe)
Here, created a dataframe by using different vectors. After, by accessing a vector to the function’row.names(), we changed the row names.
R
a= c ( "cd" , "gfg" , "ww" , "globe" ) b= c (1:4) c= c ( "f" , "g" , "h" , "i" ) print ( "original dataframe:" ) # creating dataframe df= data.frame (a,b,c) print (df) #changing the row names row.names (df)= c ( "R1" , "R2" , "R3" , "R4" ) print ( "After Modifying:" ) print (df) |
Output:
[1] "original dataframe:"
a b c
1 cd 1 f
2 gfg 2 g
3 ww 3 h
4 globe 4 i
[1] "After Modifying:"
a b c
R1 cd 1 f
R2 gfg 2 g
R3 ww 3 h
R4 globe 4 i
Conclusion
In conclusion,we learned two methods for getting row names and for setting row names by using the functions ‘dimnames()’ , ‘rownames()’ for getting and ‘rownames()’, ‘row.names() for setting in a dataframe.
Get and Set Row Names for Data Frames
In this article, we will explore various methods to Get and Set row names for Data Frames in R Programming Language.