indexing - R: Index by group and year with similar number for same group and year -


i have data frame shows births of children parent , year. need new column indexes order of birth per child, provides same number if 2 children same parent born in same year. data follows:

>df1 id       year  name parent1  2001  bas parent1  2002  jack parent2  1991  david parent3  1993  daniel parent3  1993  jasper parent3  1994  melany parent4  1997  john parent4  1999  gerard 

thus far, created index child per year per parent, children ascending numbers if born in same year. used following code:

> df2 <- df1 %>% group_by(id) %>% mutate(order = row_number(year)) > df2 id       year  name   order parent1  2001  bas    1 parent1  2002  jack   2 parent2  1991  david  1 parent3  1993  daniel 1 parent3  1993  jasper 2 parent3  1994  melany 3 parent4  1997  john   4 parent4  1999  gerard 1 

what want arrive at, however, (note double "1" parent3 in year 1993):

id       year  name   order parent1  2001  bas    1 parent1  2002  jack   2 parent2  1991  david  1 parent3  1993  daniel 1 parent3  1993  jasper 1 parent3  1994  melany 2 parent4  1997  john   3 parent4  1999  gerard 1 

do have solution problem? there slight tweak code solves this? in advance!

you can use dense_rank row_number:

df %>% group_by(id) %>% mutate(order = dense_rank(year))  # tibble: 8 x 4 # groups:   id [4] #       id  year   name order #   <fctr> <int> <fctr> <int> #1 parent1  2001    bas     1 #2 parent1  2002   jack     2 #3 parent2  1991  david     1 #4 parent3  1993 daniel     1 #5 parent3  1993 jasper     1 #6 parent3  1994 melany     2 #7 parent4  1997   john     1 #8 parent4  1999 gerard     2 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -