4

I imported an excel file with animal data that looks something like this:

AnimalID Sex Body Weight District
AB1 1 3.45 4
AB2 1 2.98 4
AB3 2 3.22 5
AB4 2 3.01 5

I want to use to use my first column(AnimaID) as rownames.

I've searched for an answer but most questions address the creation of a new column that then becomes the rownames column. I actually feel stupid coming on here and asking this. My aim is to create a pca plot using ggplot2, and that requires me to have the dataframe in the format that ggplots2 recognizes.

starball
  • 20,030
  • 7
  • 43
  • 238
max
  • 49
  • 2

2 Answers2

3

A possible solution, in base R:

rownames(df) <- df$AnimalID
df <- df[,-1]
df

#>     Sex Body.Weight District
#> AB1   1        3.45        4
#> AB2   1        2.98        4
#> AB3   2        3.22        5
#> AB4   2        3.01        5

Or using tidyverse:

library(tidyverse)

df %>% column_to_rownames("AnimalID")

#>     Sex Body.Weight District
#> AB1   1        3.45        4
#> AB2   1        2.98        4
#> AB3   2        3.22        5
#> AB4   2        3.01        5
PaulS
  • 21,159
  • 2
  • 9
  • 26
  • 1
    The first solution worked. I'm gonna bookmark this for future reference. Thank you!! – max May 22 '22 at 09:21
1

Another base option:

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

Output:

    Sex Body_Weight District
AB1   1        3.45        4
AB2   1        2.98        4
AB3   2        3.22        5
AB4   2        3.01        6
Quinten
  • 35,235
  • 5
  • 20
  • 53