Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

count occurrences of unique string row by row

say I have a df like so:

number date
123    2022-01-01
567    2022-01-01
123    2022-01-04
763    2022-01-05
567    2022-01-06
123    2022-01-09

I want to count the occurrence of each number by expanding the range row-by-row. so my expected output would be

number date        occurrence
123    2022-01-01  1
567    2022-01-01  1
123    2022-01-04  2
763    2022-01-05  1
567    2022-01-06  2
123    2022-01-09  3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

base R

dat$occurrence <- ave(dat$number, dat$number, FUN = seq_along)
dat
#   number       date occurrence
# 1    123 2022-01-01          1
# 2    567 2022-01-01          1
# 3    123 2022-01-04          2
# 4    763 2022-01-05          1
# 5    567 2022-01-06          2
# 6    123 2022-01-09          3

data.table

library(data.table)
as.data.table(dat)[, occurrence := seq_len(.N), by = number ][]
#    number       date occurrence
#     <int>     <char>      <int>
# 1:    123 2022-01-01          1
# 2:    567 2022-01-01          1
# 3:    123 2022-01-04          2
# 4:    763 2022-01-05          1
# 5:    567 2022-01-06          2
# 6:    123 2022-01-09          3

Data

dat <- structure(list(number = c(123L, 567L, 123L, 763L, 567L, 123L), date = c("2022-01-01", "2022-01-01", "2022-01-04", "2022-01-05", "2022-01-06", "2022-01-09")), row.names = c(NA, -6L), class = "data.frame")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading