Predictive Hacks

How to set the row names as a Column in R

Assume that we have the following data frame and we want to set the row names as an extra column in the data frame.

library(dplyr)

df<-data.frame(A=c(1,2,3), B=c(10,20,30))
row.names(df)<-c("A","B","C")

df
How to set the row names as a Column in R 1

We can work with the dplyr library and the rownames_to_column function as follows:

df<-df%>%rownames_to_column("NewColumn")
df
How to set the row names as a Column in R 2

As we can see, we set a new column from the row names, and we called it “NewColumn”. Now, the row names take the default values such as 1, 2, 3, ..

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore