Search code examples
rdatetimetimestampbigintegernanotime

nanotime: how to deal with NAs in a tibble?


I am using the excellent nanotime package to store my timestamps, but I am unable to make the package work when my tibble contains a missing value.

Consider this:

library(nanotime)
library(tibble)
library(dplyr)

tibble(time = c('2020-01-01 10:10:10.123456',
                NA,
                '2020-01-01 10:10:10.123456')) %>% 
  mutate(enhance = nanotime(time, 
                            tz = 'GMT', 
                            format = '%Y-%m-%d %H:%M:%E9S'))
Error in RcppCCTZ::parseDouble(x, fmt = format, tz = tz) : 
  Parse error on NA

What am I missing here? Using na.rm = TRUE does not work unfortunately.

Thanks!


Solution

  • The issue is NA is of type logical, you need to have all the values in the column of same type. We can use as.integer64 to replace logical NA's with integer64 NA.

    library(nanotime)
    
    tbl <- tibble::tibble(time = c('2020-01-01 10:10:10.123456',
                NA,
                '2020-01-01 10:10:10.123456'))
    tbl$enhance <- as.integer64(NA)
    tbl$enhance[!is.na(tbl$time)] <- nanotime(na.omit(tbl$time), tz = 'GMT',
                                     format = '%Y-%m-%d %H:%M:%E9S')
    nanotime(tbl$enhance)