Search code examples
arraysrplyrtimestamp-with-timezoneposixlt

in R, apply function to multiple inputs to return array of POSIXlt


I have a function to create a timestamp from multiple string inputs:

# Create timestamp from date, time, and timezone strings
str_to_dt <- function(date_str, time_str, tz_str){
  as.POSIXlt(x = paste(date_str, time_str), format = "%m/%d/%Y %H:%M", 
           tz = tz_str)
} 

I have arrays of input values:

dates <- c("01/23/1945", "11/11/1911")
times <- c("12:12", "13:13")
tzones <- c("Pacific/Guam", "America/New_York") 

Since as.POSIXlt takes only a constant tz, not a vector, I have to loop through these. The following for loop produces the output I would like, but I would prefer to understand how to do it in plyr.

ts <- as.POSIXlt(rep(NA,length(dates)))
for(i in 1:length(dates)){
  ts[i] <- str_to_dt(date_str = dates[i],
                    time_str = times[i],
                    tz_str = tzones[i]) 
}
ts
[1] "1945-01-23 11:11:00 GST" "1911-11-11 13:13:00 EST"   

When I use mapply I get a list of the component vectors of the datetime, which is not what I want.

mapply(FUN=str_to_dt, date_str=dates, time_str=times, tz_str=tzones) # decomposed

When I use mlply I can get a LIST of the correct 2 POSIXlt results:

library(plyr)

mlply(.data=data.frame(date_str = dates, time_str = times, 
                       tz_str = tzones, stringsAsFactors=FALSE),
           .fun=str_to_dt)

But I am at a loss getting them back into an array, since unlist totally decomposes the POSIXlt. The analogous function maply is giving me an error:

maply(.data=data.frame(date_str = dates, time_str = times, tz_str = tzones,
                       stringsAsFactors=FALSE),
           .fun=str_to_dt) # Error: Results must have one or more dimensions.

How do I fix the error so that maply works, or is there a better way?


Solution

  • c() will convert the list to a typed vector, but only if you call it indirectly.

    > d <- as.POSIXlt(Sys.Date())
    > dlist <- list(d,d)
    > do.call(c, dlist)
    [1] "2014-09-17 17:00:00 PDT" "2014-09-17 17:00:00 PDT"
    > str(do.call(c, dlist))
     POSIXlt[1:2], format: "2014-09-17 17:00:00" "2014-09-17 17:00:00"