2

我有一个带有日期列的数据框,我需要将其转换为 R 识别为日期的格式。

> dataframe
        Date        Sum
1   06/09/15       2.51
2   06/09/15       3.75
3   06/09/15       3.50
...

我首先使用以下方法对其进行了转换sapply

> dataframe$Date2<-sapply(dataframe$Date,as.Date,format="%m/%d/%y")

这将日期返回为从 1970 年 1 月 1 日开始的天数:

> dataframe
        Date        Sum      Date2
1   06/09/15       2.51      16595
2   06/09/15       3.75      16595
3   06/09/15       3.50      16595
...

后来我尝试在没有的情况下转换它sapply

> dataframe$Date3<-as.Date(dataframe$Date,format="%m/%m/%d")

这反过来又返回

> dataframe
        Date        Sum      Date2       Date3
1   06/09/15       2.51      16595  2015-09-15
2   06/09/15       3.75      16595  2015-09-15
3   06/09/15       3.50      16595  2015-09-15
...

这是两种截然不同的、明显不兼容的格式。为什么sapply返回一种格式(自起源以来的天数),而没有它返回另一种格式(%Y-%m-%d)?

现在,显然我可以忽略一种方法并继续使用sapplyas.Date但我想知道为什么它的读取方式不同。我也在努力将 Date3 向量转换为 Date2 格式。

因此,我有两个问题:

  1. 为什么sapply提供不同的日期格式?
  2. 如何将日期可识别的序列(例如 mm/dd/yyyy)转换为自 1970 年 1 月 1 日以来的天数?
4

3 回答 3

2

Here is an answer to the second part of your original question. To obtain the number of days since the epoch (1 Jan 1970) for a date in the format mm/dd/yyyy you can use the as.Date() function:

some.date <- as.Date("06/17/2015", "%m/%d/%Y")
days.since.epoch <- unclass(some.date)

> days.since.epoch
[1] 16616

Internally, R stores the date object some.date in terms of the number of days since the epoch (1 Jan 1970), and calling unclass() reveals this internal representation.

于 2015-06-17T07:43:56.410 回答
1

when working with dates I love to use lubridate as it is in my eyes much easier to use and much more intuitive then the base functions.
Your second question could be done with the following code:

require(lubridate)
dataframe$Date2<-difftime(dataframe$Date3,dmy("01-01-1970"),units="days")

depending on if you want to have the 1. January 1970 as day 1 or not you may have to add a +1 to the end of this line.

I don't really work with sapply and tapply directly (I prefer to use plyr for this) so I can't help with your first question.

于 2015-06-17T08:02:57.537 回答
1

1.

如果您不使用参数simplify=FALSEsapply将使用命令unlist将答案从列表转换为向量。unlist强制列表元素为通用类型。从手册

在可能的情况下,列表元素在取消列出期间被强制转换为通用模式,因此结果通常以字符向量结尾。向量将被强制转换为层次结构中组件的最高类型 NULL < raw <logical < integer < double < complex < character < list < 表达式:pairlists 被视为列表。

因为Date不是层次结构的一部分,unlist所以不能强制Date。我不确定为什么unlist选择强制转换为整数(而不是字符),但这可能与Date对象存储为整数的事实有关。

2.

要将 a 转换为Date自 1970 年 1 月 1 日以来的天数,您可以使用as.numeric

today=Sys.Date()
> today
[1] "2019-04-16"
> as.numeric(today)
[1] 18002

然后回去

> as.Date(18002, origin="1970-01-01")
[1] "2019-04-16"
于 2019-04-16T14:11:20.523 回答