[R] Function that create day of the year column.

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Wed Nov 5 23:35:37 CET 2014


Beware of Sys.Date, since it returns GMT, so depending on your local timezone you may be surprised by the result. I prefer to explicitly set the TZ environment variable and use Sys.time to get local time. You can use trunc() to chop off the time part.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On November 5, 2014 4:01:36 PM EST, "MacQueen, Don" <macqueen1 at llnl.gov> wrote:
>I would start with this example, which is available from base R,
>without
>additional packages, to help understand the suggestions that follow.
>
>> unclass(as.POSIXlt(Sys.Date()))
>$sec
>[1] 0
>
>$min
>[1] 0
>
>$hour
>[1] 0
>
>$mday
>[1] 5
>
>$mon
>[1] 10
>
>$year
>[1] 114
>
>$wday
>[1] 3
>
>$yday
>[1] 308
>
>$isdst
>[1] 0
>
>attr(,"tzone")
>[1] "UTC"
>
>And then see the $yday element
>
>For example:
>
>
>>   as.POSIXlt( as.Date('2014-9-13') )$yday
>[1] 255
>>   as.POSIXlt( as.Date('2014-1-1') )$yday
>[1] 0
>
>Note that the year starts with day 0, which might not be what you
>expect.
>
>If you have three columns try
>  as.POSIXlt( as.Date( paste(year, month, day, sep='-') )$yday
>
>
>Which can be illustrated by
>>   as.POSIXlt( as.Date( paste(2014, 1, 31, sep='-') ) )$yday
>[1] 30
>
>If your ³date² column is already of class Date
>   > class(Sys.Date())
>   [1] "Date"
>
>then
>  as.POSIXlt( date )$yday
>is sufficient. Otherwise you have to convert it to Date class.



More information about the R-help mailing list