0

Is there a way to convert NA values to Date.

asdd <- data.frame(a = as.Date(c(NA, "1970-01-01")), b = c(2,3))
asdd <- as.data.table(asdd)
asdd
            a b
1:       <NA> 2
2: 1970-01-01 3

asdd [,a := ifelse(is.na(a), as.Date(today()+360),a)]
asdd
       a b
1: 19580 2
2:     0 3

Expected output

asdd
       a      b
1: 2023-08-11 2
2: 1970-01-01 3

Can we achieve this ouptut?

harre
  • 7,081
  • 2
  • 16
  • 28
manu p
  • 952
  • 4
  • 10

1 Answers1

3
  1. It's almost always safer and preferred to use data.table::fifelse instead of base::ifelse, the latter has many issues (e.g., How to prevent ifelse() from turning Date objects into numeric objects).

    This is what's happening here: base::ifelse strips a vector's class, so you're losing the fact that your data is of Date class.

    If you really prefer to go this route (see number 2 below, though), try:

    asdd[, a := fifelse(is.na(a), Sys.Date() + 360, a)]
    
  2. We don't technically need it here, though, the canonical data.table method is to use subsetting assignment:

    asdd[is.na(a), a := Sys.Date() + 360]
    asdd
    #             a     b
    #        <Date> <num>
    # 1: 2023-08-11     2
    # 2: 1970-01-01     3
    
r2evans
  • 141,215
  • 6
  • 77
  • 149