Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply strptime function to every member of a data.table

I'm having trouble applying a function to every member of a data.table. Here is a simplified example:

dt <- data.table( a= c("30JAN14:23:16:00","23MAY12:02:00:00"), 
                  b=c("03AUG09:00:00:00","13JUN12:02:00:00"), 
                  c=c("31JAN14:15:19:00","23MAY12:00:00:00"))

strptime(dt[1,1,with=FALSE], "%d%B%y:%H:%M:%S")

returns "2014-01-30 23:16:00 PST"

But when I attempt to apply it across the data.table I don't get what I'm looking for and receive accusatory messages .

cols <- c("a","b","c")
dt[, (cols):=sapply(.SD, function(x) strptime(x, "%d%B%y:%H:%M:%S")),.SDcols=cols]
like image 419
Kerry Avatar asked Sep 18 '15 17:09

Kerry


1 Answers

strptime returns class POSIXlt which is actually a list which explains why using it inside either data.table or data.frame objects creates problems:

> dt[, (cols):=lapply(.SD, function(x) as.POSIXct(strptime(x, "%d%B%y:%H:%M:%S"))),.SDcols=cols]
> dt
                     a                   b                   c
1: 2014-01-30 23:16:00 2009-08-03 00:00:00 2014-01-31 15:19:00
2: 2012-05-23 02:00:00 2012-06-13 02:00:00 2012-05-23 00:00:00
like image 71
IRTFM Avatar answered Nov 14 '22 22:11

IRTFM