如何防止write.csv更改POSIXct,日期和时间类返回到字符/因素? [英] How to prevent write.csv from changing POSIXct, dates and times class back to character/factors?

查看:137
本文介绍了如何防止write.csv更改POSIXct,日期和时间类返回到字符/因素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.csv文件,每个文件有一个字段,用于日期时间,日期和时间。
原来他们都是字符字段,我已经相应地转换了它们。
在代码结尾处,如果我这样做:

  str(data)
  datetime :POSIXct 
日期:日期
时间:类'times'atomic [1:2820392](....)attr(*,format)= chrh:m:s

现在,我很高兴这个,我想创建一个.csv文件,所以这就是我有:

  write.csv(data,file =data.csv,row.names = FALSE)

我也尝试过

  write.table(data,data.csv,sep =,,row.names = FALSE)

而且,我得到的结果与两者相同,这就是我写的新的.csv的所有转换都会丢失:一切都回到了一个字符。



我怀疑我在写功能中缺少一些参数,但是我一直在搜索整个下午,我找不到什么。可以请帮忙吗?

解决方案

根据?write.table


数据框中列表或具有类(例如
日期)的列将由相应的 as.character'方法:
这样的列默认是不引用的。


简单的说,你只能写文字/字符到文本文件。如果要保留对象的二进制R表示,请使用 save


I have a .csv file with one field each for datetime, date and time. Originally they are all character fields and I have converted them accordingly. At the end of my code, if I do:

str(data)

I will get

datetime: POSIXct
date: Date
time: Class 'times'  atomic [1:2820392] (....) attr(*, "format")= chr "h:m:s"

Now, I am very happy with this and I want to create a .csv file, so this is what I have:

write.csv(data, file = "data.csv", row.names = FALSE)

I have also tried

write.table(data, "data.csv", sep = ",", row.names = FALSE)

And I get the same result with both, which is all my convertion gets lost when writing the new .csv: everything is back to being a character.

I suspect I am missing some argument in the write function, but I have been searching all afternoon and I can't find out what. Can some please help?

解决方案

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).

这篇关于如何防止write.csv更改POSIXct,日期和时间类返回到字符/因素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆