1

How can I keep the column as a date when replacing Inf values with NA?

df <- data.frame(a = structure(c(18628, Inf), class = "Date"))
df$a <- ifelse(is.infinite(df$a), NA, df$a)
df$a
MLEN
  • 2,162
  • 2
  • 20
  • 36
  • 1
    Does this answer your question? [How to prevent ifelse() from turning Date objects into numeric objects](https://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects) – caldwellst Feb 20 '22 at 09:06
  • 1
    @caldwellst actually no, because when I tried replacing my ifelse with if_else or fifelse says they are not the same type – MLEN Feb 20 '22 at 09:25
  • You can use `replace()` - `replace(df$a, is.infinite(df$a), NA)`. – Ritchie Sacramento Feb 20 '22 at 09:30

3 Answers3

1

You could wrap it into structure like you did providing your data. This is similar (but not identical) what @hadley reccomends in his comment.

structure(ifelse(is.infinite(df$a), NA, df$a), class="Date")
# [1] "2021-01-01" NA

Or less hardcoded:

structure(ifelse(is.infinite(df$a), NA, df$a), class=class(df$a))
# [1] "2021-01-01" NA

"Date" and similar classes are sometimes awkward because they are converted to numeric values; remember that and get used to it.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
1

A simple indexing operation works.

df <- data.frame(a = structure(c(18628, Inf), class = "Date"))
df$a[is.infinite(df$a)] <- NA # or df[is.infinite(df$a), 'a'] <- NA
> df
           a
1 2021-01-01
2       <NA>

> class(df$a)
[1] "Date"
sashahafner
  • 435
  • 1
  • 7
1

why not just wrap NA in as.Date?

data.table::fifelse(is.infinite(df$a), as.Date(NA), df$a)

OR

dplyr::if_else(is.infinite(df$a),as.Date(NA), df$a)
langtang
  • 22,248
  • 1
  • 12
  • 27