我遇到了计算列表中日期差异的问题。我将在两点上提出我的问题:
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" ...
我如何将上一个问题的答案应用于每个对象?
我希望我的问题足够明确!
谢谢!
答案 0 :(得分:2)
不需要lapply
,只需unlist
并使用diff
,其中包含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
答案 1 :(得分: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