Here is one method. With this, the result has to be a string, otherwise unlist()
or c()
will turn the result back to the system timezone for every element in the list.
It's still slow though because it is not vectorized.
> get_local_time <- function(timestamp_utc, local_tz) {
l <- lapply(seq(length(timestamp_utc)),
function(x) {format(with_tz(timestamp_utc[x], local_tz[x]), "%FT%T%z")})
unlist(l)
}
> mutate(data, timestamp_local = get_local_time(timestamp_utc, tzone = local_tz))
Source: local data frame [3 x 3]
timestamp_utc local_tz timestamp_local
(time) (chr) (chr)
1 2015-11-18 03:55:04 America/New_York 2015-11-17T22:55:04-0500
2 2015-11-18 03:55:08 America/Los_Angeles 2015-11-17T19:55:08-0800
3 2015-11-18 03:55:10 America/Indiana/Indianapolis 2015-11-17T22:55:10-0500
Update 2015-11-24
Using dplyr::combine()
rather than unlist()
allows the variable to remain datetimes with the right timezone attributes rather than converting to strings.
> get_local_time <- function(timestamp_utc, local_tz) {
l <- lapply(seq(length(timestamp_utc)),
function(x) {with_tz(timestamp_utc[x], local_tz[x])})
combine(l)
}
> mutate(data, timestamp_local = get_local_time(timestamp_utc, tzone = local_tz))
Source: local data frame [3 x 3]
timestamp_utc local_tz timestamp_local
(time) (chr) (time)
1 2015-11-18 03:55:04 America/New_York 2015-11-17T22:55:04
2 2015-11-18 03:55:08 America/Los_Angeles 2015-11-17T19:55:08
3 2015-11-18 03:55:10 America/Indiana/Indianapolis 2015-11-17T22:55:10