Substitute DataFrame Row Names by Values in Vector in R
Last Updated :
30 Sep, 2021
In this article, we will discuss how to substitute dataframe row names by values in a vector in R programming language.
Dataframe in use:
We can substitute row names by using rownames() function
Syntax:
rownames(dataframe) <- vector
where,
- dataframe is the input dataframe
- vector is the new row values
Example: R program to substitute the rownames of the dataframe
R
data = data.frame (sub1= c (100, 89, 90, 78, 98, 93),
sub2= c (89, 91, 97, 67, 100, 89))
vec = c (10, 20, 30, 40, 50, 60)
rownames (data) = vec
print (data)
|
Output:
Example: R program to substitute the rownames of the dataframe
R
data = data.frame (sub1= c (100, 89, 90, 78, 98, 93),
sub2= c (89, 91, 97, 67, 100, 89))
vec = c ( "row1" , "row2" , "row3" , "row4" , "row5" , "row6" )
rownames (data) = vec
print (data)
|
Output:
We can also replace the row names by values in a dataframe
Syntax:
rownames(dataframe) <- dataframe$column_name
where
- dataframe is the input dataframe
- column_name is the column of the dataframe
Example: R program to substitute rownames of the dataframe using column
R
data = data.frame (sub1= c (100, 89, 90, 78, 98, 93),
sub2= c (89, 91, 97, 67, 100, 79))
rownames (data) = data$sub1
print (data)
rownames (data) = data$sub2
print (data)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...