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

Time:09-17

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

CodePudding user response:

thx Chris, works fine! one forther Question: there is another column with the birth-month. is it possible to make a further statement reffering to this column (birth-month), if the persons have the same birthyear. Like: if the persons x and y from family i have the same birth-year, than the birthmonth is deciding for the statement first-born or not?

CodePudding user response:

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