[R] day, month, year functions

Gabor Grothendieck ggrothendieck at gmail.com
Fri Aug 11 01:22:14 CEST 2006


Here are three ways:

xx <- as.Date("2006-01-05")

# 1. use as.POSIXlt
as.POSIXlt(xx)$mday
as.POSIXlt(xx)$mon + 1
as.POSIXlt(xx)$year + 1900

# 2. use format
as.numeric(format(xx, "%d"))
as.numeric(format(xx, "%m"))
as.numeric(format(xx, "%Y"))

# 3. use month.day.year in chron package
library(chron)
month.day.year(unclass(xx))$day
month.day.year(unclass(xx))$month
month.day.year(unclass(xx))$year

Also see the help desk article in R News 4/1.


On 8/10/06, Horace Tso <Horace.Tso at pgn.com> wrote:
> Hi list,
>
> I'm trying to turn a date into something productive. (Not what you may be thinking....)
>
> I want three functions so I could take a "date" object and get the day of week, month, and year from it.
>
> xx <- as.Date("2006-01-05")
>
> month(xx) equal 1
> day(xx) equal 5
> year(xx) equal 2006
>
> I'm aware of the weekdays() and months() functions in the base package. But they return a character object which requires some coding to convert into a numeric value.
>
> I've also tried the sday.of.week() in fCalendar but it doesn't like my date,
>
> > sday.of.week(xx)
> Error in Ops.Date(sdates, 10000) : %/% not defined for Date objects
>
> Do these functions exist in some package I'm not aware of?
>
> Thanks in adv.
>
> Horace Tso



More information about the R-help mailing list