3

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?

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134
  • you could probably just sapply over the list that mlply gives you to get it into a vector. something like sapply(mlplyResult, function(entry) entry[[1]]), easy hack – DMT Sep 18 '14 at 18:14
  • Are you looking for `Map(FUN=str_to_dt, date_str=dates, time_str=times, tz_str=tzones`? – agstudy Sep 18 '14 at 18:23

1 Answers1

1

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"
Neal Fultz
  • 9,282
  • 1
  • 39
  • 60
  • Accepted as a viable workaround. Still not sure how to fix `maply`. It turns out since I have ~1M observations I am better off using `data.frame` and the `IDateTime` class. Thanks--J – C8H10N4O2 Sep 20 '14 at 10:35