Create numbered sequence for occurrences of a given nesting variable

℡╲_俬逩灬. 提交于 2019-12-02 08:38:29

问题


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())


来源:https://stackoverflow.com/questions/25072483/create-numbered-sequence-for-occurrences-of-a-given-nesting-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!