我有一堆具有不同时区的时间日期 - 我能够生成一个数据框,其中这些作为不同的列。它看起来像这样
timedate <- c("2024-03-31T03:14:00", "2024-03-24T01:07:00", "2024-04-09T22:45:00")
zones <- c("UTC", "Australia/Brisbane", "Australia/Canberra")
df <- tibble(timedate, zones)
df
> A tibble: 3 × 2
> timedate zones
> <chr> <chr>
> 1 2024-03-31T03:14:00 UTC
> 2 2024-03-24T01:07:00 Australia/Brisbane
> 3 2024-04-09T22:45:00 Australia/Canberra
我知道以下工作可以创建 POSIX 类数据的列...
df <- mutate(df
,timedatezone = as.POSIXct(timedate,format="%Y-%m-%dT%H:%M", tz = 'UTC'))
df
> A tibble: 3 × 3
> timedate zones timedatezone
> <chr> <chr> <dttm>
> 1 2024-03-31T03:14:00 UTC 2024-03-31 03:14:00
> 2 2024-03-24T01:07:00 Australia/Brisbane 2024-03-24 01:07:00
> 3 2024-04-09T22:45:00 Australia/Canberra 2024-04-09 22:45:00
但是...以下则不然
df <- mutate(df
,timedatezone = as.POSIXct(timedate,format="%Y-%m-%dT%H:%M", tz = zones))
> Error in `mutate()`:
> In argument: `timedatezone = as.POSIXct(timedate, format = "%Y-%m-%dT%H:%M", tz = zones)`.
> Caused by error in `strptime()`:
> invalid 'tz' value
> Run `rlang::last_trace()` to see where the error occurred.
我觉得我错过了一些非常基本的东西,但我用谷歌搜索了又搜索,但我无法找到解决办法
我期待它能发挥作用
也许:
df |>
rowwise() |>
mutate(timedatezone = as.POSIXct(timedate, format="%Y-%m-%dT%H:%M", tz = zones)) |>
ungroup()
结果
# A tibble: 3 × 3
timedate zones timedatezone
<chr> <chr> <dttm>
1 2024-03-31T03:14:00 UTC 2024-03-31 03:14:00
2 2024-03-24T01:07:00 Australia/Brisbane 2024-03-23 15:07:00
3 2024-04-09T22:45:00 Australia/Canberra 2024-04-09 12:45:00