简体   繁体   English

R as.POSIXct 转换为 as.Date

[英]R as.POSIXct conversion to as.Date

I'm dealing with a data.frame object that holds in the first column a 'Date' field.我正在处理一个 data.frame 对象,该对象在第一列中包含一个“日期”字段。 Initially, I converted all the dates (which came in 'Date' as plain string) to POSIXct dates applying as.POSIXct() , but then I realized that as.Date was sufficient to my purpose.最初,我将所有日期(以纯字符串形式出现在 'Date' 中)转换为应用as.POSIXct() POSIXct 日期,但后来我意识到 as.Date 足以满足我的目的。 So I apply the as.Date() function to the POSIXct dates and I get a strange result: all the dates are scaled back one day ('2020-07-02 01:00:00' --> '2020-07-01').因此,我将as.Date()函数应用于 POSIXct 日期,但得到了一个奇怪的结果:所有日期都缩减了一天 ('2020-07-02 01:00:00' --> '2020-07- 01')。 Also tried with as.Date.POSIXct() with the same result.还尝试使用as.Date.POSIXct()获得相同的结果。
Is there something I've missed in the conversion?我在转换中遗漏了什么吗? Is this type of conversion legitim?这种转换合法吗?
Thanks谢谢

Without knowing exactly what the data looks like, my best guess would have to do with the origin date used in the as.Date() function call when you convert from POSIXct.在不确切知道数据是什么样子的情况下,我最好的猜测与从 POSIXct 转换时 as.Date() 函数调用中使用的原始日期有关。 Hadley explains here the POSIXct and POSIXlt data types are really just double float values representing number of seconds since 1970-01-01. Hadley在这里解释说,POSIXct 和 POSIXlt 数据类型实际上只是表示自 1970 年 1 月 1 日以来的秒数的双浮点值。 According to ?as.Date, if you're converting a value of class numeric, you should supply a value to the origin argument.根据 ?as.Date,如果您要转换类 numeric 的值,您应该为 origin 参数提供一个值。

You could just reload your raw data, and play around with as.Date() and as.POSIXct() and see how the origin argument plays into an accurate conversion.您可以重新加载原始数据,然后使用 as.Date() 和 as.POSIXct() 进行操作,看看 origin 参数如何进行准确的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM