Extract date elements from POSIXlt and put into data frame in R
Try this (DF as your data.frame):
extractdate <- function(date) {
day <- format(date, format="%d")
month <- format(date, format="%m")
year <- format(date, format="%Y")
cbind(day, month, year)
}
cbind(DF, extractdate(DF$dd_mmm_yy))
If you are using the data.table
package, it already has functions to extract data time components from POSIXct.
second(x)
minute(x)
hour(x)
yday(x)
wday(x)
mday(x)
week(x)
isoweek(x)
month(x)
quarter(x)
year(x)
The use is straightforward (e.g. dt[, day := day(dd_mmm_yy)]
). You can see the full documentation here.
POSIXlt
objects are a list of 9 components (see the Details section of ?POSIXlt
for more information). Because the dd_mmm_yy
column is POSIXlt
, you don't need a function to extract the components. You can just extract the components by their names:
orders$day <- orders$dd_mmm_yy$mday # day of month
orders$month <- orders$dd_mmm_yy$mon+1 # month of year (zero-indexed)
orders$year <- orders$dd_mmm_yy$year+1900 # years since 1900
orders
# order_id dd_mmm_yy day month year
# 1 1 2005-07-28 28 7 2005
# 2 2 2007-03-04 4 3 2007
One liner using lubridate
require(plyr); require(lubridate)
mutate(mydf, date = ymd(dd_mmm_yy), day = day(date),
month = month(date), year = year(date))
order_id dd_mmm_yy date day month year
1 1 2005-07-28 2005-07-28 28 7 2005
2 2 2007-03-04 2007-03-04 4 3 2007