lundi 4 novembre 2019

combining 2 columns using ifelse dropping a variable R

I am trying to combine the male and female columns I have created into one column. I tried using some answers I found on stack, but the second sex I queried was excluded.

Build Data Frame: ID <- 1:10 SPAYDT <- c("", "2011-12-01", "", "2006-05-01", "", "", "", "", "", "") SPAYDTU <- c(1,NA,NA,NA,NA,NA,NA,NA,NA,NA,) NEUTDT <- c("", "", "", "", "", "", "2013-03-01", "", "", "") NEUTDTU <- c(NA,NA,NA,1,NA,NA,NA,NA,NA,NA,) df <- as.data.frame(rbind(ID, SPAYDT, SPAYDTU, NEUTDT, NEUTDTU) df

The goal is to have a column for sex, formated as a factor with 2 levels - Male and Female It should say female if the SPAYDT or SPAYDTU have a value in them, and male if the NEUTDT or NEUTDTU have a value in them. What I have tried:

  • using a nested if-else statement to build one sex column
  • making two columns then combining using

    df$male <-
    ifelse(NEUTDT!="", "Male",
    ifelse(NEUTDTU=1, "Male", NA))
    df$female <-
    ifelse(SPAYDT!="", "Female",
    ifelse(SPAYDTU==1, "Female", NA))
    df$sex <- ifelse(!is.na(df$female), df$female, df$male)
    

and df$sex <- ifelse(SPAYDT!="", "Female", ifelse(SPAYDTU==1, "Female", ifelse(NEUTDT!="", "Male", ifelse(NEUTDTU=1, "Male", NA))))

However, no matter what I do, the sex column at the end only has one sex. I made sure my df was attached for use of column names as variables. I tried restarting R and running the setup code again. I just don't know why the ifelse statement is ignoring the second sex input.

Any help is greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire