[R] Loop With Dates
Jim Lemon
drj|m|emon @end|ng |rom gm@||@com
Sat Sep 21 12:37:09 CEST 2019
Hi Phillip,
While I really like Ana's solution, this might also help:
phdf<-read.table(text="Date count
2018-03-29 1
2018-03-29 1
2018-03-29 1
2018-03-30 1
2018-03-30 1
2018-03-30 1
2018-03-31 1
2018-03-31 1
2018-03-31 1",
header=TRUE,stringsAsFactors=FALSE)
phdf$Date<-as.Date(phdf$Date,"%Y-%m-%d")
incflag<-diff(phdf$Date)>0
phdf$count<-c(NA,cumsum(incflag)+1)
Jim
On Sat, Sep 21, 2019 at 3:47 AM Phillip Heinrich <herd_dog using cox.net> wrote:
>
> With the data snippet below I’m trying to increment the “count” vector by one each time the date changes.
>
> Date count
> 1 2018-03-29 1
> 2 2018-03-29 1
> 3 2018-03-29 1
> 81 2018-03-30 1
> 82 2018-03-30 1
> 83 2018-03-30 1
> 165 2018-03-31 1
> 166 2018-03-31 1
> 167 2018-03-31 1
>
>
> >
>
>
>
> I can get count to change when the date changes with the following code:
>
> test2 <- transform(test2,
> + count = ifelse(Date == lag(Date,1),count,count+1))
> > test2
> Date count
> 1 2018-03-29 NA
> 2 2018-03-29 1
> 3 2018-03-29 1
> 81 2018-03-30 2
> 82 2018-03-30 1
> 83 2018-03-30 1
> 165 2018-03-31 2
> 166 2018-03-31 1
> 167 2018-03-31 1
>
>
>
>
>
>
>
> ...but I want all three March 30 rows to have a count of 2 and the March 31 rows to be equal to 3. Any suggestions?
>
> Thanks.
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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