Convert the values in a column into row names in an existing data frame in R

I would like to convert the values in a column of an existing data frame into row names. Is it 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

thanks

Answered by Andrew Jenkins

To make first column row names in r data frame, you can do the following:

#To create the data frame:

df<-data.frame(names=LETTERS[1:5], Var.1=1:5,Var.2=5:1,Var.3=0:4 )

> df

  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

> rownames(df) <- df[,1] #Assigning row names from 1st column

> df[,1] <- NULL #Removing the first column

> df

  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



Your Answer

Interviews

Parent Categories