[R] Create previous dates from date with consideration of leap year
Lee, Chel Hee
chl948 at mail.usask.ca
Thu Dec 11 17:34:44 CET 2014
The sample data you provided has the variable 'date'. Since the type of
this variable is 'factor', you may try to convert type of variable from
'factor' to 'date' as shown in the below:
> x$rval <- as.Date(x$date, format="%d%b%Y")-5
> x
id date case rval
1 1 27apr1993 1 1993-04-22
2 2 13feb2005 1 2005-02-08
3 3 29may2002 1 2002-05-24
4 4 22sep2005 1 2005-09-17
5 5 18dec1991 1 1991-12-13
6 6 07jun2010 1 2010-06-02
7 7 07jul1991 1 1991-07-02
8 8 04feb2008 1 2008-01-30
9 9 31jan2005 1 2005-01-26
10 10 01feb2003 1 2003-01-27
11 11 29jan2009 1 2009-01-24
12 12 03mar2008 1 2008-02-27
>
Leap year is also considered (See the last case 'id=12'). Is this what
you are looking for? I hope this helps.
Chel Hee Lee
On 12/11/2014 9:54 AM, Kuma Raj wrote:
> Dear R Community,
>
> I wish to create 5 preceding dates from the date variable by ID. How
> could I create such dates? The code should consider leap year.
>
> Thanks
>
> Sample data follows:
>
>
> structure(list(id = 1:12, date = structure(c(9L, 6L, 11L, 8L,
> 7L, 5L, 4L, 3L, 12L, 1L, 10L, 2L), .Label = c("01feb2003", "03mar2008",
> "04feb2008", "07jul1991", "07jun2010", "13feb2005", "18dec1991",
> "22sep2005", "27apr1993", "29jan2009", "29may2002", "31jan2005"
> ), class = "factor"), case = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
> 1L, 1L, 1L, 1L)), .Names = c("id", "date", "case"), class =
> "data.frame", row.names = c(NA,
> -12L))
>
> ______________________________________________
> R-help at 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