温温酱
使用data.table,并假设您希望通过date在personid子集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如果你不想dateDT[, 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以下任何一项都将有效DT[, id := seq_along(measurement), by = personid]DT[, id := seq_along(date), by = personid]使用的等效命令plyrlibrary(plyr)# ordering by dateddply(Data, .(personid), mutate, id = order(date))# in original orderddply(Data, .(personid), mutate, id = seq_along(date))ddply(Data, .(personid), mutate, id = seq_along(measurement))