Convert 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.
For example this is the iris dataset:

 > data 
     Species Var.1 Var.2 Var.3
 1     Setosa      1     5     0
 2     Setosa      2     4     1
 3     Virginica   3     3     2
 4     Virginica   4     2     3
 5     Virginica   5     1     4

and I want something like this:

> data.with.rownames 
       Var.1 Var.2 Var.3
Setosa    1     5     0
Setosa    2     4     1
Virginica 3     3     2
Virginica 4     2     3
Virginica 5     1     4

This is my actual code:

data <- iris
row.names(data) <- data[,5]

but it doesn't work. I have this error:

Error in `.rowNamesDF<-`(x, value = value) : 
 duplicate 'row.names' are not allowed
In addition: Warning message:
non-unique values when setting 'row.names': ‘setosa’, ‘versicolor’, ‘virginica’

how can I fix it?

This is the key thing - rownames need to be unqiue much like column headers. You can't have two columns named "x" and you can't have two rows named "x". In the case of the iris dataset you're trying to set the rownames to be equal to the Species column, but there are only three unique values for 150 rows.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.