1

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!

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.