Convert column values ​​to row names in an existing data frame in R

I would like to convert the values ​​in a column of an existing data frame to row names. Is it possible to do this without exporting the data frame and then re-import it by calling row.names = ?

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 

at

 > 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 

thank

+85
r
Apr 05 2018-11-11T00:
source share
5 answers

This should do:

 samp2 <- samp[,-1] rownames(samp2) <- samp[,1] 

In short, there is no alternative to reassignment.

Edit: By correcting yourself, you can also do this in place: assign the rowname attributes, and then delete the column:

 R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10]) R> rownames(df) <- df[,1] R> df[,1] <- NULL R> df bc a 1 A b 2 B c 3 C d 4 D e 5 E f 6 F g 7 G h 8 H i 9 I j 10 J R> 
+110
Apr 05 2018-11-11T00:
source share

Since 2016, you can also use tidyverse .

 library(tidyverse) samp %>% remove_rownames %>% column_to_rownames(var="names") 
+20
Mar 29 '17 at 20:14
source share

in one line

 > samp.with.rownames <- data.frame(samp[,-1], row.names=samp[,1]) 
+19
Nov 07 '13 at 9:20
source share

You can accomplish this in 2 simple statements:

 row.names(samp) <- samp$names samp[1] <- NULL 
+3
Apr 09 '18 at 20:32
source share

It seems that the single-line has become even simpler (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 deleted automatically.

0
Mar 28 '19 at 4:10
source share



All Articles