44

How can we generate unique id numbers within each group of a dataframe? Here's some data grouped by "personid":

personid date measurement
1         x     23
1         x     32
2         y     21
3         x     23
3         z     23
3         y     23

I wish to add an id column with a unique value for each row within each subset defined by "personid", always starting with 1. This is my desired output:

personid date measurement id
1         x     23         1
1         x     32         2
2         y     21         1
3         x     23         1
3         z     23         2
3         y     23         3

I appreciate any help.

Frank
  • 65,012
  • 8
  • 95
  • 173
suresh
  • 457
  • 1
  • 4
  • 5

6 Answers6

41

Some dplyr alternatives, using convenience functions row_number and n.

library(dplyr)
df %>% group_by(personid) %>% mutate(id = row_number())
df %>% group_by(personid) %>% mutate(id = 1:n())
df %>% group_by(personid) %>% mutate(id = seq_len(n()))
df %>% group_by(personid) %>% mutate(id = seq_along(personid))

You may also use getanID from package splitstackshape. Note that the input dataset is returned as a data.table.

getanID(data = df, id.vars = "personid")
#    personid date measurement .id
# 1:        1    x          23   1
# 2:        1    x          32   2
# 3:        2    y          21   1
# 4:        3    x          23   1
# 5:        3    z          23   2
# 6:        3    y          23   3
Henrik
  • 61,039
  • 13
  • 131
  • 152
  • The `dplyr` solutions are good. But if, like me, you keep getting weird errors when trying this approach, make sure that you are not getting conflicts between `plyr` and `dplyr` as explained [in this post](https://stackoverflow.com/questions/33593791/dplyr-row-number-error-in-rank) It can be avoided by explicitly calling `dplyr::mutate(...)` – EcologyTom Apr 10 '18 at 14:12
  • 1
    @EcologyTom Indeed. See also [Why does summarize or mutate not work when I load `plyr` after `dplyr`?](https://stackoverflow.com/questions/26106146/why-does-summarize-or-mutate-not-work-when-i-load-plyr-after-dplyr) – Henrik Apr 10 '18 at 14:18
  • You are right, I'm surprised I haven't run into this sort of problem before. I had not consciously called `plyr`, it was probably still loaded from a couple of days ago. Thanks for your answer! – EcologyTom Apr 10 '18 at 14:24
32

The misleadingly named ave() function, with argument FUN=seq_along, will accomplish this nicely -- even if your personid column is not strictly ordered.

df <- read.table(text = "personid date measurement
1         x     23
1         x     32
2         y     21
3         x     23
3         z     23
3         y     23", header=TRUE)

## First with your data.frame
ave(df$personid, df$personid, FUN=seq_along)
# [1] 1 2 1 1 2 3

## Then with another, in which personid is *not* in order
df2 <- df[c(2:6, 1),]
ave(df2$personid, df2$personid, FUN=seq_along)
# [1] 1 1 1 2 3 2
Josh O'Brien
  • 154,425
  • 26
  • 353
  • 447
18

Using data.table, and assuming you wish to order by date within the personid subset

library(data.table)
DT <- data.table(Data)

DT[,id := order(date), by  = personid]

##    personid date measurement id
## 1:        1    x          23  1
## 2:        1    x          32  2
## 3:        2    y          21  1
## 4:        3    x          23  1
## 5:        3    z          23  3
## 6:        3    y          23  2

If you wish do not wish to order by date

DT[, id := 1:.N, by = personid]

##    personid date measurement id
## 1:        1    x          23  1
## 2:        1    x          32  2
## 3:        2    y          21  1
## 4:        3    x          23  1
## 5:        3    z          23  2
## 6:        3    y          23  3

Any of the following would also work

DT[, id := seq_along(measurement), by =  personid]
DT[, id := seq_along(date), by =  personid]

The equivalent commands using plyr

library(plyr)
# ordering by date
ddply(Data, .(personid), mutate, id = order(date))
# in original order
ddply(Data, .(personid), mutate, id = seq_along(date))
ddply(Data, .(personid), mutate, id = seq_along(measurement))
mnel
  • 110,110
  • 27
  • 254
  • 248
7

I think there's a canned command for this, but I can't remember it. So here's one way:

> test <- sample(letters[1:3],10,replace=TRUE)
> cumsum(duplicated(test))
 [1] 0 0 1 1 2 3 4 5 6 7
> cumsum(duplicated(test))+1
 [1] 1 1 2 2 3 4 5 6 7 8

This works because duplicated returns a logical vector. cumsum evalues numeric vectors, so the logical gets coerced to numeric.

You can store the result to your data.frame as a new column if you want:

dat$id <- cumsum(duplicated(test))+1
Ari B. Friedman
  • 69,285
  • 35
  • 174
  • 232
5

Assuming your data are in a data.frame named Data, this will do the trick:

# ensure Data is in the correct order
Data <- Data[order(Data$personid),]
# tabulate() calculates the number of each personid
# sequence() creates a n-length vector for each element in the input,
# and concatenates the result
Data$id <- sequence(tabulate(Data$personid))
Joshua Ulrich
  • 168,168
  • 29
  • 327
  • 408
3

You can use sqldf

df<-read.table(header=T,text="personid date measurement
1         x     23
1         x     32
2         y     21
3         x     23
3         z     23
3         y     23")

library(sqldf)
sqldf("SELECT a.*, COUNT(*) count
       FROM df a, df b 
       WHERE a.personid = b.personid AND b.ROWID <= a.ROWID 
       GROUP BY a.ROWID"
)

#  personid date measurement count
#1        1    x          23     1
#2        1    x          32     2
#3        2    y          21     1
#4        3    x          23     1
#5        3    z          23     2
#6        3    y          23     3
shhhhimhuntingrabbits
  • 7,267
  • 2
  • 22
  • 23