Create numbered sequence for occurrences of a give

2019-03-01 11:58发布

问题:

I'm hoping to add to a data set a variable that sequences the instances a certain grouping variable appears. For example:

ids <- c(rep(1,4),rep(2,6),rep(3,2))

I'm wanting another variable that would count the instances each id appears. Creating a vector like this:

1,2,3,4,1,2,3,4,5,6,1,2

With them combined looking something like this:

    ids count
1    1      1
2    1      2
3    1      3
4    1      4
5    2      1
6    2      2
7    2      3
8    2      4
9    2      5
10   2      6
11   3      1
12   3      2

Any ideas? Many thanks!

回答1:

I suggest ave with seq_along

ids <- c(rep(1,4),rep(2,6),rep(3,2))
count <- ave(ids,ids, FUN=seq_along)
cbind(ids, count)

#       ids count
#  [1,]   1     1
#  [2,]   1     2
#  [3,]   1     3
#  [4,]   1     4
#  [5,]   2     1
#  [6,]   2     2
#  [7,]   2     3
#  [8,]   2     4
#  [9,]   2     5
# [10,]   2     6
# [11,]   3     1
# [12,]   3     2


回答2:

Or if it is ordered

cbind(ids, count=sequence(unname(table(ids))))
#       ids count
#  [1,]   1     1
#  [2,]   1     2
#  [3,]   1     3
#  [4,]   1     4
#  [5,]   2     1
#  [6,]   2     2
#  [7,]   2     3
#  [8,]   2     4
#  [9,]   2     5
# [10,]   2     6
# [11,]   3     1
# [12,]   3     2

Or

  cbind(ids,within.list(rle(ids), lengths <- sequence(lengths))$lengths)

Or

 library(data.table)
 dt <- as.data.table(ids)
 dt[,count:=seq_len(.N), by=ids]

Or

library(dplyr)
dat <- data.frame(ids)
dat %>% 
group_by(ids) %>%
mutate(count=row_number())