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
CodePudding user response:
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), )
# [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.
CodePudding user response:
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"
CodePudding user response:
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)