[R] Finding the last value before a certain date
William Dunlap
wdunlap at tibco.com
Thu Jul 19 17:29:18 CEST 2012
If you need to do this for a lot of dates findInterval() will do
it faster. E.g.,
> f <- function(dates, data) {
+ i <- findInterval(dates, data$date)
+ i[i==0] <- NA # before first data$date
+ data[i, ]
+ }
> xx <- as.Date(c("2010-10-06", "2010-10-25", "2009-01-01", "2011-12-31"))
> cbind(xx, f(xx, dat))
xx date y
2 2010-10-06 2010-10-04 1968
5 2010-10-25 2010-10-24 3496
NA 2009-01-01 <NA> NA
6 2011-12-31 2010-10-31 3958
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
> Behalf Of Rui Barradas
> Sent: Thursday, July 19, 2012 1:11 AM
> To: Robert Latest
> Cc: r-help at r-project.org
> Subject: Re: [R] Finding the last value before a certain date
>
> Hello,
>
> Try the following.
>
>
> dat <- read.table(text="
> date y
> 1 2010-09-27 1356
> 2 2010-10-04 1968
> 3 2010-10-11 2602
> 4 2010-10-17 3116
> 5 2010-10-24 3496
> 6 2010-10-31 3958
> ", header=TRUE, stringsAsFactors=FALSE)
>
> dat$date <- as.Date(dat$date)
> str(dat)
> search <- as.Date("2010-10-06")
> max(which(dat$date <= search))
> dat$y[ix]
>
>
> Hope this helps,
>
> Rui Barradas
>
> Em 19-07-2012 08:42, Robert Latest escreveu:
> > Hello all,
> >
> > I have a dataframe that looks like this:
> >
> > head(df)
> > date y
> > 1 2010-09-27 1356
> > 2 2010-10-04 1968
> > 3 2010-10-11 2602
> > 4 2010-10-17 3116
> > 5 2010-10-24 3496
> > 6 2010-10-31 3958
> >
> > I need a function that, given any date, returns the y value
> > corresponding to the given date or the last day before the given date.
> >
> > Example:
> >
> > Input: as.Date("2010-10-06"). Output: 1968 (because the last value is
> > from 2010-10-04)
> >
> > I've been tinkering with this for an hour now, without success. I
> > think the solution is either surprisingly complicated or surprisingly
> > simple.
> >
> > Thanks,
> > robert
> >
> > ______________________________________________
> > 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.
> >
>
> ______________________________________________
> 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