How to prevent write.csv from changing POSIXct, dates and times class back to character/factors?

妖精的绣舞 提交于 2019-12-01 01:18:52

According to ?write.table:

Any columns in a data frame which are lists or have a class (e.g. dates) will be converted by the appropriate 'as.character' method: such columns are unquoted by default.

Simply put, you can only write text/characters to text files. Use save if you want to preserve the binary R representation of your object(s).

If you want to preserve all of the time information so it can be read in again, this recipe should work:

dat <- data.frame(time=as.POSIXlt("2013-04-25 09:00 BST"), quantity=1)
dat2 <- dat
dat2$time <- format(dat2$time, usetz=TRUE)
write.csv(dat2, "time.csv", row.names=FALSE)

It gives the following CSV file:

"time","quantity"
"2013-04-25 09:00:00 BST",1

in which the timezone information is presented explicitly; if you apply write.csv to the original dat, the formatting is lost.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!