您可以完成此任务,但最终会在新列中添加列表。当你有多个时区时,你必须比平时多工作一点。您需要的是连续遍历每个时间和时区并创建一个新的时间戳。您的样本数据称为mydf。在下面的代码中,我首先创建了一个日期对象,因为time_stemp 是mydf 中的字符。然后,对于每一行,取时间和时区并使用with_tz()。 map2() 正在处理这项工作。你也可以使用mapply()。由于map2() 返回列表,我最后使用了unnest()。
library(tidyverse)
library(lubridate)
mutate(mydf, time_stamp = as.POSIXct(time_stamp, format = "%Y-%m-%d %H:%M:%S", tz = "UTC"),
new_time = map2(.x = time_stamp, .y = time_zone,
.f = function(x, y) {with_tz(time = x, tzone = y)}))
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 10 obs. of 3 variables:
$ time_stamp: POSIXct, format: "2020-02-06 07:08:59" "2020-02-06 07:43:50" "2020-02-06 08:44:51" "2020-02-06 08:45:07" ...
$ time_zone : chr "America/Chicago" "America/Denver" "America/New_York" "America/New_York" ...
$ new_time :List of 10
..$ : POSIXct, format: "2020-02-06 01:08:59"
..$ : POSIXct, format: "2020-02-06 00:43:50"
..$ : POSIXct, format: "2020-02-06 03:44:51"
..$ : POSIXct, format: "2020-02-06 03:45:07"
..$ : POSIXct, format: "2020-02-06 03:45:10"
..$ : POSIXct, format: "2020-02-06 03:45:14"
..$ : POSIXct, format: "2020-02-06 03:45:30"
..$ : POSIXct, format: "2020-02-06 02:45:47"
..$ : POSIXct, format: "2020-02-06 03:45:48"
..$ : POSIXct, format: "2020-02-06 03:45:49"
如果您不介意将日期用作字符,则可以执行以下操作。
mutate(mydf, time_stamp = as.POSIXct(time_stamp, format = "%Y-%m-%d %H:%M:%S", tz = "UTC"),
new_time = map2(.x = time_stamp, .y = time_zone,
.f = function(x, y) {as.character(with_tz(time = x, tzone = y))})) %>%
unnest(new_time)
time_stamp time_zone new_time
<dttm> <chr> <chr>
1 2020-02-06 07:08:59 America/Chicago 2020-02-06 01:08:59
2 2020-02-06 07:43:50 America/Denver 2020-02-06 00:43:50
3 2020-02-06 08:44:51 America/New_York 2020-02-06 03:44:51
4 2020-02-06 08:45:07 America/New_York 2020-02-06 03:45:07
5 2020-02-06 08:45:10 America/New_York 2020-02-06 03:45:10
6 2020-02-06 08:45:14 America/New_York 2020-02-06 03:45:14
7 2020-02-06 08:45:30 America/New_York 2020-02-06 03:45:30
8 2020-02-06 08:45:47 America/Chicago 2020-02-06 02:45:47
9 2020-02-06 08:45:48 America/New_York 2020-02-06 03:45:48
10 2020-02-06 08:45:49 America/New_York 2020-02-06 03:45:49
数据
mydf <- structure(list(time_stamp = c("2020-02-06 07:08:59", "2020-02-06 07:43:50",
"2020-02-06 08:44:51", "2020-02-06 08:45:07", "2020-02-06 08:45:10",
"2020-02-06 08:45:14", "2020-02-06 08:45:30", "2020-02-06 08:45:47",
"2020-02-06 08:45:48", "2020-02-06 08:45:49"), time_zone = c("America/Chicago",
"America/Denver", "America/New_York", "America/New_York", "America/New_York",
"America/New_York", "America/New_York", "America/Chicago", "America/New_York",
"America/New_York")), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))