[r] Convert the values in a column into row names in an existing data frame

I would like to convert the values in a column of an existing data frame into row names. Is is possible to do this without exporting the data frame and then reimporting it with a row.names = call?

For example I would like to convert:

 > samp 
     names Var.1 Var.2 Var.3
 1     A     1     5     0
 2     B     2     4     1
 3     C     3     3     2
 4     D     4     2     3
 5     E     5     1     4

Into:

> samp.with.rownames 
     Var.1 Var.2 Var.3
A     1     5     0
B     2     4     1
C     3     3     2
D     4     2     3
E     5     1     4

This question is related to r

The answer is


You can execute this in 2 simple statements:

row.names(samp) <- samp$names
samp[1] <- NULL

As of 2016 you can also use the tidyverse.

library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")

It looks like the one-liner got even simpler along the line (currently using R 3.5.3):

# generate original data.frame
df <- data.frame(a = letters[1:10], b = 1:10, c = LETTERS[1:10])
# use first column for row names
df <- data.frame(df, row.names = 1)

The column used for row names is removed automatically.


in one line

> samp.with.rownames <- data.frame(samp[,-1], row.names=samp[,1])