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

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

df<-df%>%rownames_to_column("NewColumn")
df

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

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s