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

Add column with repeated numbers per group

I want to add a new column with a 3-number repeat 1,1,1,2,2,2,3,3,3 until the end of each group (Chr) within the data frame. This would be easy if all the groups can be divided by 3, but I am not sure how to do this when the group length is divisible by 2. What happens with the last repeat within each group?

original <- data.frame(Chr=c("chr1","chr1","chr1","chr1","chr1","chr2","chr2","chr2","chr2","chr2","chr3"),
           value=c(1,3,1,3,5,6,3,1,3,5,0),
           seq=c(1,2,3,4,5,1,2,3,4,5,6))

modified <- data.frame(Chr=c("chr1","chr1","chr1","chr1","chr1","chr2","chr2","chr2","chr2","chr2","chr3"),
                       value=c(1,3,1,3,5,6,3,1,3,5,0),
                       seq=c(1,2,3,4,5,1,2,3,4,5,6),
                       rep=c(1,1,1,2,2,1,1,1,2,2,1))

>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

We could use gl() function:

library(dplyr)

original %>% 
  mutate(rep = as.integer(gl(n(),3,n())), .by=Chr) 
    Chr value seq group
1  chr1     1   1     1
2  chr1     3   2     1
3  chr1     1   3     1
4  chr1     3   4     2
5  chr1     5   5     2
6  chr2     6   1     1
7  chr2     3   2     1
8  chr2     1   3     1
9  chr2     3   4     2
10 chr2     5   5     2
11 chr3     0   6     1
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