Apply if else condition to make new column in r to separte individuals in a group

Viewed 55

I'd like to use an if else statement to make a new column in my dataframe based on data in another column. Namely, I want to make a differentiation IN a group. So for example in a family with an ID xyz with 2 siblings with their own ID but the same family ID the oldest person (based on the year) the predicate "first born" and the other person "not first born. Should look then as follows:

the way it should look like

Thx for any coding help

1 Answers

You can group_by ID_family and ifelse:

library(dplyr)
df %>%
  group_by(ID_family) %>%
  mutate(New = ifelse(birthyear == min(birthyear),
                      "firstborn", "not firstborn"))
# A tibble: 4 × 4
# Groups:   ID_family [2]
  ID_person ID_family birthyear New          
      <dbl>     <dbl>     <dbl> <chr>        
1       100         1      1990 firstborn    
2       200         1      1991 not firstborn
3       300         2      1967 firstborn    
4       400         2      1968 not firstborn
Related