[R] Changing date format

Jim Lemon jim at bitwrit.com.au
Thu Oct 9 10:54:03 CEST 2014


On Wed, 8 Oct 2014 04:49:02 PM Frederic Ntirenganya wrote:
> The idea is that I want the non-leap years to be 366 days instead of 
being
> 365 days. ie. Each year must have 366 days.
> 
> for example: in the column Start2, Apr 18 will be Apr 17.
> 
> > head(Samaru)
> 
>   Year Start End Length Start2   End2
> 1 1930   108 288    180 Apr 18 Oct 15
> 2 1931   118 288    170 Apr 28 Oct 15
> 3 1932   115 295    180 Apr 24 Oct 21
> 4 1933   156 294    138 Jun 05 Oct 21
> 5 1934   116 291    175 Apr 26 Oct 18
> 6 1935   134 288    154 May 14 Oct 15
> 
> Is there a way to that in R?
> 
Hi Frederic,
That doesn't sound like a good idea to me. Instead of having about 
one quarter of the dates wrong, you will have about three quarters 
wrong. When I check the code I sent you:

Samaru$Start<-format(as.Date(
 paste(Samaru$Year,"01-01",sep="-"))+Samaru$Start-1,"%b %d")
Samaru$End<-format(as.Date(
 paste(Samaru$Year,"01-01",sep="-"))+Samaru$End-1, "%b %d")

it appears to correct for leap years. If you really want to do it yourself,
you can get a list of leap years here:

http://kalender-365.de/leap-years.php

I think the simplest way is to correct your Start and End fields before 
doing the calculation:

# create a vector of leap years
leap_years<-c(1804,1808,1812,1816,1820,1824,1828,...,2400)
# subtract 1 from Start entries in leap years and
# equal to or greater than 1 March
Samaru$Start<-Samaru$Start -
 (Samaru$Year %in% leap_years & Samaru$Start > 59)
# same for End
Samaru$End<-Samaru$End -
 (Samaru$Year %in% leap_years & Samaru$End > 59)

However, I don't think you have to worry about leap years if you are 
using the code I sent.

Jim



More information about the R-help mailing list