1

我遇到了计算列表中日期差异的问题。我将在两点上提出我的问题:

1.

我有一个日期向量。我想找出彼此跟随的每两个日期之间的天数差异。例如,在 date1 和 date2 之间,然后是 date2 和 3,然后是 3 和 4... 由于 strptime 函数似乎只适用于 2 个日期,我如何计算这对日期之间的天数差异?

[1] "2011-10-06" "2011-09-28" "2011-09-20" "2011-08-29" "2011-09-09" "2011-08-16"
[7] "2011-08-05" "2011-07-28" "2011-07-18" "2011-07-06" "2011-06-27" "2011-06-17"
[13] "2011-06-03" "2011-05-22" "2011-05-02" "2011-05-12" "2011-04-21" "2011-04-11"
[19] "2011-04-01" "2011-03-23

2.

这些日期包含在这样的列表中:

 $ 2008: chr [1:17] "2008-05-22" "2008-05-30" "2008-06-09" "2008-06-18" ...
 $ 2003: chr [1:23] "2003-04-24" "2003-05-15" "2003-05-23" "2003-06-05" ...
 $ 2005: chr [1:22] "2005-04-22" "2005-05-07" "2005-05-14" "2005-05-22" ...
 $ 2006: chr [1:24] "2006-04-14" "2006-04-19" "2006-05-03" "2006-05-11" ...
 $ 2007: chr [1:15] "2007-06-15" "2007-04-27" "2007-05-11" "2007-05-22" ...
 $ 2004: chr [1:20] "2004-05-18" "2004-06-04" "2004-06-09" "2004-06-18" ...
 $ 2009: chr [1:19] "2009-05-05" "2009-05-19" "2009-05-29" "2009-06-10" ...
 $ 2010: chr [1:18] "2010-09-28" "2010-09-20" "2010-09-10" "2010-09-01" ...
 $ 2011: chr [1:20] "2011-10-06" "2011-09-28" "2011-09-20" "2011-08-29" ...

我如何将上一个问题的答案应用于每个对象?

我希望我的问题足够清楚!

谢谢!

4

2 回答 2

2

不需要lapply, 只需unlistand use diffwhich 具有Date类对象的方法...

dates <- as.list( c( "2011-10-06","2011-09-28","2011-09-20","2011-08-29","2011-09-09","2011-08-16","2011-08-05","2011-07-28","2011-07-18","2011-07-06","2011-06-27","2011-06-17","2011-06-03","2011-05-22","2011-05-02","2011-05-12","2011-04-21","2011-04-11","2011-04-01","2011-03-23" ) )

diff( as.Date( unlist(dates) ) )
#Time differences in days
# [1]  -8  -8 -22  11 -24 -11  -8 -10 -12  -9 -10 -14 -12 -20  10 -21 -10 -10  -9
于 2013-07-11T14:25:44.953 回答
1

您还可以使用filter

filter(dt,c(1,-1))

例如 :

dt <- scan(text='"2011-10-06" "2011-09-28" "2011-09-20" "2011-08-29" "2011-09-09" "2011-08-16"
"2011-08-05" "2011-07-28" "2011-07-18" "2011-07-06" "2011-06-27" "2011-06-17"
"2011-06-03" "2011-05-22" "2011-05-02" "2011-05-12" "2011-04-21" "2011-04-11"
"2011-04-01" "2011-03-23"',what='chracter')
dt <- as.Date(dt)
filter(dt,c(1,-1))
Time Series:
Start = 1 
End = 20 
Frequency = 1 
 [1]  -8  -8 -22  11 -24 -11  -8 -10 -12  -9 -10 -14 -12 -20  10 -21 -10 -10  -9  NA
于 2013-07-11T14:32:21.790 回答