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

Adding the first, second, third observation in a data frame

I am working with a dataset containing serial numbers. I would like to add a column that defines if it is the first, second or nth time that the serial number occurs. For example:

serial   occurrence
   110            1
   111            1
   112            1
   110            2
   110            3

>Solution :

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

You can use the following code:

df <- data.frame(serial = c(110, 111, 112, 110, 110))

library(dplyr)

df %>% 
  group_by(serial) %>% 
  mutate(occurence=1:n())

Output:

# A tibble: 5 × 2
# Groups:   serial [3]
  serial occurence
   <dbl>     <int>
1    110         1
2    111         1
3    112         1
4    110         2
5    110         3
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