1

I have a dataset that looks like this:

id  time
1   1
1   2
2   5
2   3
3   2
3   7
3   8

And I want to add another column to show me how many observations there are in a group.

id  time label
1   1   1
1   2   2
2   5   1
2   3   2
3   2   1
3   7   2
3   8   3
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Preet Rajdeo
  • 377
  • 1
  • 5
  • 11

1 Answers1

1

We can use ave

df1$label <- with(df1, ave(seq_along(id), id, FUN=seq_along))

Or with dplyr

library(dplyr)
df1 %>%
    group_by(id) %>%
    mutate(label = row_number())
akrun
  • 874,273
  • 37
  • 540
  • 662