Convert row names into first column

2019-01-03 05:40发布

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 the row names into the first column. Currently I use something like this to make row names as the first column:

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

Is there a single line to do this?

4条回答
可以哭但决不认输i
2楼-- · 2019-01-03 06:06

Alternatively, you can create a new dataframe (or overwrite the current one, as the example below) so you do not need to use of any external package. However this way may not be efficient with huge dataframes.

df <- data.frame(names = row.names(df), df)
查看更多
小情绪 Triste *
3楼-- · 2019-01-03 06:11

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

library(dplyr)
df <- add_rownames(df, "VALUE")

UPDATE (mid-2016):

add_rownames() has been deprecated and is being replaced by tibble::rownames_to_column() (same functions, but Hadley refactored dplyr a bit).

查看更多
Bombasti
4楼-- · 2019-01-03 06:17

A one line option is :

df$names <- rownames(df)
查看更多
Summer. ? 凉城
5楼-- · 2019-01-03 06:23

You can both remove row names and convert them to a column by reference (without reallocating memory using ->) 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
查看更多
登录 后发表回答