我有一个包含日期时间字符串列的数据框:
library(tidyverse)
library(lubridate)
testdf = data_frame(
mytz = c('Australia/Sydney', 'Australia/Adelaide', 'Australia/Perth'),
mydt = c('2018-01-17T09:15:00', '2018-01-17T09:16:00', '2018-01-17T09:18:00'))
testdf
# A tibble: 3 x 2
# mytz mydt
# <chr> <chr>
# 1 Australia/Sydney 2018-01-17T09:15:00
# 2 Australia/Adelaide 2018-01-17T09:16:00
# 3 Australia/Perth 2018-01-17T09:18:00
我想将这些日期时间字符串转换为具有各自时区的 POSIX 日期时间对象:
testdf %>% mutate(mydt_new = ymd_hms(mydt, tz = mytz))
Error in mutate_impl(.data, dots) : Evaluation error:
tz
argument must be a single character string. In addition: Warning message: In if (tz != "UTC") { : the condition has length > 1 and only the first element will be used
如果我使用
ymd_hms
,我会得到相同的结果没有时区并将其通过管道输入 force_tz
.就时区操作而言,lubridate 不支持任何类型的矢量化的结论是否公平?
最佳答案
另一种选择是 map2
.存储不同的可能更好tz
输出 list
因为这可能会被强制为单个 tz
library(tidyverse)
out <- testdf %>%
mutate(mydt_new = map2(mydt, mytz, ~ymd_hms(.x, tz = .y)))
如果需要,可以是
unnest
编辑out %>%
unnest
list
中的值是out %>%
pull(mydt_new)
#[[1]]
#[1] "2018-01-17 09:15:00 AEDT"
#[[2]]
#[1] "2018-01-17 09:16:00 ACDT"
#[[3]]
#[1] "2018-01-17 09:18:00 AWST"
关于r - 使用 lubridate 进行矢量化时区转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48291932/