njtierney / naniar

Tidy data structures, summaries, and visualisations for missing data
http://naniar.njtierney.com/
Other
650 stars 54 forks source link

Feature request: replace_with_na function which doesn't strip attributes (with code!) #275

Closed antondutoit closed 3 years ago

antondutoit commented 3 years ago

Like vbrazao in #244, I have had replace_with_na turn factors into integers. (Attribute stripping is the kryptonite of the tidyverse if you ask me ..). So I would like a replace_with_na function which doesn't strip attributes.

The code below might be a start. It writes NA where there is an empty cell, but ignores POSIX columns because they cause an error. (I guess to fix that you would have to coerce the POSIX cols into a different class, replace the empty cells then coerce back to POSIX?)

library(tidyverse)
library(lubridate)

df <- data.frame(dates = as.POSIXlt.Date(c(12345, 23456, 34567)), alpha=2:4, beta=c("", "", 6), gamma=c(7:8,""), 
delta = c("", FALSE, TRUE), chars = c("a", "bb", ""))

df <- df %>%
    mutate_if(purrr::negate(is.POSIXt), ~ na_if(., ""))
njtierney commented 3 years ago

Thanks for the code, this is related to #244 but I'll close both these issues once it is resolved. In the future I think it is fine for you to contribute your code on that same thread 😄

Thanks again for posting an issue here, it'll be a few weeks as I return from holiday.

antondutoit commented 3 years ago

Will do. Actually I'll repeat-post there so vbrazao sees it.

njtierney commented 3 years ago

If you repeat post there you can close this one to save time later 😄