0

Basically, I have a dataset of bird bands, with one or more instances of each color.band code per year. I want to have a column that counts up one digit each time a given color.band code occurs. So if XXXXXX occurs two times, the first one would have a 1 next to it and the second one a 2. If YYYYYY had only one occurrence it would only have a 1, and so on. I'm not sure how to begin doing this. How could I do this? Thank you!

part of my dataset showing the color.bands in question

neilfws
  • 32,751
  • 5
  • 50
  • 63
Sarah Hays
  • 33
  • 6
  • Welcome to Stack Overflow. Please [make this question reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by including example data in a plain text format - for example the output from `dput(yourdata)`. We cannot copy/paste data from images. – neilfws Nov 23 '20 at 22:35
  • Do you want to count `color.band` across all years or within years? – neilfws Nov 23 '20 at 22:39

2 Answers2

0

We can use ave

df1$Count <- with(df1, ave(seq_along(color.band), color.band, FUN = seq_along))

Or using rowid from data.table

library(data.table)
df1$Count <- rowid(df1$color.band)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

A dplyr solution, where mydata is your dataframe.

If you want to count across all years:

library(dplyr)
mydata %>% 
  group_by(color.band) %>% 
  mutate(Count = row_number()) %>%
  ungroup()

If you want to count within years:

mydata %>% 
  group_by(year, color.band) %>% 
  mutate(Count = row_number()) %>%
  ungroup()
neilfws
  • 32,751
  • 5
  • 50
  • 63