[R] Matching Dates Closest without going over

Gabor Grothendieck ggrothendieck at gmail.com
Sat Oct 10 14:20:42 CEST 2009


Create two zoo series, merge them and use na.locf (last occurence
carried forward):
library(zoo)

z1 <- zoo(as.numeric(d1), d1)
z2 <- zoo(as.numeric(d2), d2)
z <- merge(z1, z2)

z.na.locf <- na.locf(z, na.rm = FALSE)[time(z1)]

transform(as.data.frame(z.na.locf), z1 = as.Date(z1), z2 = as.Date(z2))


# Note that if the real situation is that you have two input zoo
series, z1 and z2,
# that you wish to merge then its really only this:

na.locf(merge(z1, z2), na.rm = FALSE)[time(z1)]


See the help files for merge.zoo, na.locf.zoo and the three zoo
vignettes for more.


On Sat, Oct 10, 2009 at 12:14 AM, ampc <ampc2008 at gmail.com> wrote:
>
> Hi,
>
> I have 2 date vectors d1 and d2.
>
> d1 <- structure(c(14526, 14495, 14464, 14433, 14402, 14371, 14340, 14309,
> 14278, 14247, 14216, 14185), class = "Date")
> d2 <- structure(c(14526, 14509, 14488, 14466, 14453, 14441, 14396, 14388,
> 14343, 14333, 14310, 14281), class = "Date")
>
> I would like to create another dataframe with columns d1 and d2, where d1 is
> the original d1 and d2 is the max(d2) such that d1 > d2. And NA's where not
> applicable.
> (See desired result below)
>
> Thanks,
> Ampy
>
>
>
> d1
> 2009-10-09
> 2009-09-08
> 2009-08-08
> 2009-07-08
> 2009-06-07
> 2009-05-07
> 2009-04-06
> 2009-03-06
> 2009-02-03
> 2009-01-03
> 2008-12-03
> 2008-11-02
>
>
> d2
> 2009-10-09
> 2009-09-22
> 2009-09-01
> 2009-08-10
> 2009-07-28
> 2009-07-16
> 2009-06-01
> 2009-05-24
> 2009-04-09
> 2009-03-30
> 2009-03-07
> 2009-02-06
>
> result:
>
> d1                         d2
> 2009-10-09           2009-10-09
> 2009-09-08           2009-09-01
> 2009-08-08           2009-07-28
> 2009-07-08           2009-06-01
> 2009-06-07           2009-06-01
> 2009-05-07           2009-04-09
> 2009-04-06           2009-03-30
> 2009-03-06           2009-02-06
> 2009-02-03           NA
> 2009-01-03           NA
> 2008-12-03           NA
> 2008-11-02           NA
>
> --
> View this message in context: http://www.nabble.com/Matching-Dates-Closest-without-going-over-tp25830902p25830902.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list