NAs in case_when output dependent on order using dplyr in R

Viewed 37

Can anyone explain why the code below produces NAs in c for b1 but values for b2? I can't see why it depends on the order of vector a, given c in both b1 and b2 has the same type.

a1 = c("a", "2022", "2023")
a2 = c("2022", "a", "2023")
b1 = tibble(a1)
b2 = tibble(a2)

b1 %>% 
  mutate(c = case_when(
    !is.na(as.numeric(a1)) ~ as.Date(paste0(a1,"-01-01"), optional = TRUE),
    TRUE ~ as.Date(NA)
  ))

b2 %>% 
  mutate(c = case_when(
    !is.na(as.numeric(a2)) ~ as.Date(paste0(a2,"-01-01"), optional = TRUE),
    TRUE ~ as.Date(NA)
  ))
1 Answers

Specify the format as well because in the first case, the value that is not a Date is the first element. It is mentioned in the ?as.Date

format - ... If not specified, it will try tryFormats one by one on the first non-NA element, and give an error if none works.

library(dplyr)
b1 %>% 
   mutate(c = case_when(!is.na(as.numeric(a1)) 
     ~ as.Date(paste0(a1, '-01-01'), format = "%Y-%m-%d")))

-output

# A tibble: 3 × 2
  a1    c         
  <chr> <date>    
1 a     NA        
2 2022  2022-01-01
3 2023  2023-01-01

Or just take out the as.Date outside the case_when

b1 %>% 
   mutate(c = as.Date(case_when(
     !is.na(as.numeric(a1)) ~ paste0(a1,"-01-01")  )))
Related