Rdatatable / data.table

R's data.table package extends data.frame:
http://r-datatable.com
Mozilla Public License 2.0
3.52k stars 967 forks source link

fread column with only NA values as POSIXct returns warning and a character column #6208

Open markus-schaffer opened 2 weeks ago

markus-schaffer commented 2 weeks ago

I would like to read a column of a NA values as POSIXct using fread.

I would expect this to work:

library(data.table)
fwrite(data.table(datetime = as.POSIXct(NA)), "test.csv")
fread("test.csv", colClasses = "POSIXct")

However, this gives the following warning:

Warning message:
Column 'datetime' was requested to be 'POSIXct' but fread encountered the following error:
    character string is not in a standard unambiguous format
so the column has been left as type 'character' 

In contrast using utils::write.csv and utils::read.csv this works:

write.csv(data.frame(datetime = as.POSIXct(NA)), "test.csv", row.names = FALSE)
read.csv("test.csv", colClasses = "POSIXct")

Output of sessionInfo()

R version 4.4.1 (2024-06-14 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 10 x64 (build 19045)

Matrix products: default

locale:
[1] LC_COLLATE=Danish_Denmark.utf8  LC_CTYPE=Danish_Denmark.utf8    LC_MONETARY=Danish_Denmark.utf8 LC_NUMERIC=C                    LC_TIME=Danish_Denmark.utf8    

time zone: Europe/Copenhagen
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] data.table_1.15.4

loaded via a namespace (and not attached):

[1] compiler_4.4.1    tools_4.4.1       rstudioapi_0.16.0

I have also posted this at stackoverflow

ben-schwen commented 2 weeks ago

The underlying problem is that as.POSIXct("") is not working, which it should IMO.