mardi 16 mars 2021

Using ifelse changes output it is not supposed to change

ID <- 1:10
YOB <- c("2000", "2001", "2001", "2002", "2002", "2004", "2005", "2007", "2008", "2008")
born_before <- c("FALSE", "FALSE", "TRUE", "NA", "FALSE", "NA", "TRUE", "TRUE", "FALSE", "NA") 
df <- data.frame(ID, YOB, born_before)

I am trying to use an ifelse statement to change year of birth (YOB) to blanks if an individual is born before either of its parents (if born_before is true). If born_before is NA, I would also like to change YOB to a blanks. However, with this piece of code

df$YOB <- with(df, ifelse(born_before == TRUE, YOB == "", YOB))

my YOB gets changed completely to different numbers. The resulting dataframe looks like this

ID YOB born_before
1 1 FALSE
2 2 FALSE
3 0 TRUE
4 3 NA
5 3 FALSE
6 4 NA
7 0 TRUE
8 0 TRUE
9 7 FALSE
10 7 NA

when it should like this one

ID YOB born_before
1 2000 FALSE
2 2001 FALSE
3 TRUE
4 NA
5 2002 FALSE
6 NA
7 TRUE
8 TRUE
9 2008 FALSE
10 NA

Any ideas what is going wrong? I am a novice R user (have dabbled a bit) and would like to learn. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire