Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr::if_else - check for condition and insert NA as part of the evaluation

Tags:

r

dplyr

I'm trying to solve a simple problem. I check for a particular condition and if it is true I insert a date value or else insert NA (i.e. leave a blank cell).

To get this to work, I'm using if_else but it is stubbornly refusing to work (and I have invested a couple of hours reading SO and help pages).

This is what I have tried and failed:

library(tidyverse)
library(lubridate)

df <- data.frame(date   = dmy(c("01/01/2019", "02/01/2019", "03/01/2019")),
           status = c("Active", "Suspended", "Active"),
           stringsAsFactors = FALSE)

  df %>%  mutate(sus_date = if_else(status == "suspended", 1, 2))   # This works

  df %>% mutate(sus_date = if_else(status == "suspended", date, NA)) # Throws an Error
  Error: `false` must be a `Date` object, not a logical vector
  Call `rlang::last_error()` to see a backtrace.


  df %>% mutate(sus_date = if_else(status == "suspended", date, NA_real_)) # Throws an error
  Error in as.Date.numeric(value) : 'origin' must be supplied

This seem like a trivial problem and should not have taken so long to find an answer!

Any ideas how to do this?

ps. I want to avoid using base::ifelse as it changes the date format

like image 503
cephalopod Avatar asked Dec 18 '22 15:12

cephalopod


1 Answers

you can coerce the NA into date too, ie:

df %>% mutate(sus_date = if_else(status == "Suspended", date, ymd(NA))) 
        date    status   sus_date
1 2019-01-01    Active       <NA>
2 2019-01-02 Suspended 2019-01-02
3 2019-01-03    Active       <NA>
like image 148
KU99 Avatar answered May 26 '23 09:05

KU99