rkevinburton at charter.net
2009-Oct-27 21:49 UTC
[R] Year and Month extraction from Date object.
Hello, I have seen much discussion on Date. But I can't seem to do this simple operation. I can convert a string to a date: d <- as.Date(DATE, format="%m/%d/%Y") But what I want to do is extract the year and month so I can construct an element in a ts object. Ideally I would like to see d$year but that doesn't seem to be available. Once I have a Date object how can I get an integer year? Thank you. Kevin
?weekdays contains Note: Other components such as the day of the month or the year are very easy to compute: just use ?as.POSIXlt? and extract the relevant component. (d <- Sys.Date()) 1900 + as.POSIXlt(d)$year 1 + as.POSIXlt(d)$mon should get you started. On Tue, 27 Oct 2009, rkevinburton at charter.net wrote:> Hello, > > I have seen much discussion on Date. But I can't seem to do this > simple operation. I can convert a string to a date: > > d <- as.Date(DATE, format="%m/%d/%Y") > > But what I want to do is extract the year and month so I can > construct an element in a ts object. Ideally I would like to see > d$year but that doesn't seem to be available. Once I have a Date > object how can I get an integer year? > > Thank you. > > Kevin-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, stats.ox.ac.uk/~ripley University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595
On Tue, 2009-10-27 at 14:49 -0700, rkevinburton at charter.net wrote:> Hello, > > I have seen much discussion on Date. But I can't seem to do this > simple operation. I can convert a string to a date: > > d <- as.Date(DATE, format="%m/%d/%Y") > > But what I want to do is extract the year and month so I can construct > an element in a ts object. Ideally I would like to see d$year but that > doesn't seem to be available. Once I have a Date object how can I get > an integer year?as.numeric(format(d, format = "%Y")) as.numeric(format(d, format = "%m")) and so on. Look at the formats in ?strftime for further details. HTH G> > Thank you. > > Kevin > > ______________________________________________ > R-help at r-project.org mailing list > stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.-- %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~% Dr. Gavin Simpson [t] +44 (0)20 7679 0522 ECRC, UCL Geography, [f] +44 (0)20 7679 0565 Pearson Building, [e] gavin.simpsonATNOSPAMucl.ac.uk Gower Street, London [w] ucl.ac.uk/~ucfagls UK. WC1E 6BT. [w] freshwaters.org.uk %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%