rif-statementmutated

Mutate with ifelse multiple conditions in R


I have dataframe like below

monkey = data.frame(girl = 1:10, kn = NA, boy = 5)

And i want to understand the following code meaning step by step

monkey %>%
  mutate(t = ifelse(is.na(kn),.[,grepl('a',names(.))],ll))

Thank you everyone in advance for your support.


Solution

  • In my opinion, this is not good code, but I'll try to explain what it is doing.

    Ultimately, this code is not defensive-enough to be safe (base-vs-tibble variant) and its intent is unclear.

    My advice when using dplyr is to use dplyr::if_else instead of base R's ifelse. For one, ifelse has some issues and limitations (e.g., How to prevent ifelse() from turning Date objects into numeric objects); for another, if_else protects you from ambiguous, inconsistent-results code such as in your question.