On Fri, Mar 13, 2015 at 11:36 AM, Kumsaa <waddee...@gmail.com> wrote: > How could I extract both month and year from a date? I know how to > separately extract both using lubridate package: > > df$month <- month(df$date) > df$year<- year(df$date) > > I wish to extract year and month as one column > >> dput(mydf) > structure(list(date = structure(c(14975, 14976, 14977, 14978, > 14979, 14980, 14981, 14982, 14983, 14984, 14985, 14986, 14987, > 14988, 14989, 15340, 15341, 15342, 15343, 15344, 15345, 15346, > 15347, 15348, 15349, 15350, 15351, 15352, 15353, 15354), class = "Date"), > temp = c(6.5140544091004, 3.69073712745884, 3.04839429519466, > 9.16988228171461, -1.17176248610603, 2.88216040747883, > 4.98853844809017, > 4.07520306701834, 9.82902813943658, 2.79305715971987, 8.04721677924611, > 7.50667729759095, 2.91055000121842, 1.65559895014064, 4.8019596483372, > 16.2567986804179, 13.3352908067145, 16.6955807821108, 6.28373374879922, > 6.97181051627531, 5.74282686202818, 4.37018386569785, 12.5725962512824, > 4.6583055309578, 8.76457542037641, 10.7070862034423, 12.84023567151, > 5.78620621848167, 5.98643374478599, 13.0993210289842)), .Names = > c("date", > "temp"), row.names = c(NA, 30L), class = "data.frame") >
The zoo package has a "yearmon" class that represents dates as year and month with no day: > library(zoo) > transform(mydf, yearmon = as.yearmon(date)) date temp yearmon 1 2011-01-01 6.514054 Jan 2011 2 2011-01-02 3.690737 Jan 2011 3 2011-01-03 3.048394 Jan 2011 4 2011-01-04 9.169882 Jan 2011 5 2011-01-05 -1.171762 Jan 2011 6 2011-01-06 2.882160 Jan 2011 etc. ______________________________________________ R-help@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.