Convert row names to first column

I have a data frame like this:

df VALUE ABS_CALL DETECTION P-VALUE 1007_s_at "957.729231881542" "P" "0.00486279317241156" 1053_at "320.632701283368" "P" "0.0313356324173416" 117_at "429.842323161046" "P" "0.0170004527476119" 121_at "2395.7364289242" "P" "0.0114473584876183" 1255_g_at "116.493632746934" "A" "0.39799368200131" 1294_at "739.927122116896" "A" "0.0668649772942343" 

I want to convert row names to the first column. I am currently using something like this so that the row names are in the first column:

  d <- df names <- rownames(d) rownames(d) <- NULL data <- cbind(names,d) 

Is there one line?

+106
r dataframe col rowname
Apr 08 '15 at 9:45
source share
6 answers

You can remove row names and convert them to a column by reference (without reallocating memory with -> ) using setDT and its keep.rownames = TRUE argument from the data.table package

 library(data.table) setDT(df, keep.rownames = TRUE)[] # rn VALUE ABS_CALL DETECTION P.VALUE # 1: 1 1007_s_at 957.7292 P 0.004862793 # 2: 2 1053_at 320.6327 P 0.031335632 # 3: 3 117_at 429.8423 P 0.017000453 # 4: 4 121_at 2395.7364 P 0.011447358 # 5: 5 1255_g_at 116.4936 A 0.397993682 # 6: 6 1294_at 739.9271 A 0.066864977 

As @snoram mentioned, you can give the new column any name you want, for example, setDT(df, keep.rownames = "newname") will add "newname" as the row column.

+93
Apr 08 '15 at 9:53 on
source share

Or you can use dplyr add_rownames which does the same thing as David:

 library(dplyr) df <- tibble::rownames_to_column(df, "VALUE") 

UPDATE (mid 2016): (included in the above)

the old function called add_rownames() deprecated and replaced by tibble::rownames_to_column() (the same functions, but Hadley reorganized dplyr ).

+102
Apr 08 '15 at 10:04
source share

One line option:

 df$names <- rownames(df) 
+66
Mar 18 '16 at 12:21
source share

Alternatively, you can create a new data frame (or overwrite the current one, as an example below), so you do not need to use any external package. However, this method may be inefficient with huge data frames.

 df <- data.frame(names = row.names(df), df) 
+20
Mar 30 '17 at 17:55
source share

Moved my comment in response to the sentence above:

You do not need additional packages, here is a single line:

 d <- cbind(rownames(d), data.frame(d, row.names=NULL)) 
+5
Mar 27 '19 at 13:43
source share

dplyr::as_data_frame(df, rownames = "your_row_name") will give you an even simpler result.

+1
Jun 01 '19 at 15:37
source share



All Articles