0

I would like to make an ID number for each unique name. Data could look like this:

dat <- read.table(text='name    value   etc1    etc2
                          A        9      20       X
                          A       10      10       X
                          A       11       1       Y
                          B        2       5       Y
                          C       40      40       Y
                          C       50       2       Y',header=TRUE)

What I mean is that I would like to create a new column ID which is 1 when name is "A", 2 when name is B so forth. The result should look like this:

  dat <- read.table(text=' ID    name    value   etc1    etc2
                           1      A        9      20       X
                           1      A       10      10       X
                           1      A       11       1       Y
                           2      B        2       5       Y
                           3      C       40      40       Y
                           3      C       50       2       Y',header=TRUE)

My data frame is much bigger than this example, so what I am looking for is a general solution. Hope someone can help, I have no clue on how to start.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Mathy
  • 167
  • 1
  • 8
  • 2
    In your case just `as.numeric(dat$name)` will work. Maybe a bit more general solution could be `library(data.table) ; setDT(dat)[, ID := .GRP, by = name]` or just `match(dat$name, unique(dat$name))` – David Arenburg Oct 26 '15 at 09:29
  • 3
    This has been asked countless times before. First Google hit: http://stackoverflow.com/questions/9289258/how-to-create-id-column-in-r – SimonG Oct 26 '15 at 09:33

0 Answers0