使用 dplyr 语法和 attr 函数转换时区
Converting timezone using dplyr syntax and attr function
我正在尝试仅使用 dplyr 语法和 attr 函数来转换时区,而不加载其他包。
代表:
dt1 <- as.POSIXct("2010-01-01 08:00:00", tz = "GMT")
dt <- seq(dt1, length = 10, by = "1 day")
我可以使用 attr 转换成正确的时区:
attr(dt, "tzone")
[1] "GMT"
attr(dt, "tzone") <- "Australia/Sydney" # convert to intended tz
我感兴趣的是如何将 attr 合并到 dplyr::mutate 语法中?
就可链式解决方案而言(我假设这就是您所说的 "using dplyr syntax" 的意思),您可以像
中那样使用 .POSIXct
library(magrittr)
dt %>% .POSIXct(tz = "Australia/Sydney")
#[1] "2010-01-01 19:00:00 AEDT" "2010-01-02 19:00:00 AEDT"
#[3] "2010-01-03 19:00:00 AEDT" "2010-01-04 19:00:00 AEDT"
#[5] "2010-01-05 19:00:00 AEDT" "2010-01-06 19:00:00 AEDT"
#[7] "2010-01-07 19:00:00 AEDT" "2010-01-08 19:00:00 AEDT"
#[9] "2010-01-09 19:00:00 AEDT" "2010-01-10 19:00:00 AEDT"
这是一个最小的 dplyr::mutate
示例
data.frame(dt = dt) %>%
mutate(dt_Australia = .POSIXct(dt, tz = "Australia/Sydney"))
# dt dt_Australia
#1 2010-01-01 08:00:00 2010-01-01 19:00:00
#2 2010-01-02 08:00:00 2010-01-02 19:00:00
#3 2010-01-03 08:00:00 2010-01-03 19:00:00
#4 2010-01-04 08:00:00 2010-01-04 19:00:00
#5 2010-01-05 08:00:00 2010-01-05 19:00:00
#6 2010-01-06 08:00:00 2010-01-06 19:00:00
#7 2010-01-07 08:00:00 2010-01-07 19:00:00
#8 2010-01-08 08:00:00 2010-01-08 19:00:00
#9 2010-01-09 08:00:00 2010-01-09 19:00:00
#10 2010-01-10 08:00:00 2010-01-10 19:00:00
我正在尝试仅使用 dplyr 语法和 attr 函数来转换时区,而不加载其他包。
代表:
dt1 <- as.POSIXct("2010-01-01 08:00:00", tz = "GMT")
dt <- seq(dt1, length = 10, by = "1 day")
我可以使用 attr 转换成正确的时区:
attr(dt, "tzone")
[1] "GMT"
attr(dt, "tzone") <- "Australia/Sydney" # convert to intended tz
我感兴趣的是如何将 attr 合并到 dplyr::mutate 语法中?
就可链式解决方案而言(我假设这就是您所说的 "using dplyr syntax" 的意思),您可以像
中那样使用.POSIXct
library(magrittr)
dt %>% .POSIXct(tz = "Australia/Sydney")
#[1] "2010-01-01 19:00:00 AEDT" "2010-01-02 19:00:00 AEDT"
#[3] "2010-01-03 19:00:00 AEDT" "2010-01-04 19:00:00 AEDT"
#[5] "2010-01-05 19:00:00 AEDT" "2010-01-06 19:00:00 AEDT"
#[7] "2010-01-07 19:00:00 AEDT" "2010-01-08 19:00:00 AEDT"
#[9] "2010-01-09 19:00:00 AEDT" "2010-01-10 19:00:00 AEDT"
这是一个最小的 dplyr::mutate
示例
data.frame(dt = dt) %>%
mutate(dt_Australia = .POSIXct(dt, tz = "Australia/Sydney"))
# dt dt_Australia
#1 2010-01-01 08:00:00 2010-01-01 19:00:00
#2 2010-01-02 08:00:00 2010-01-02 19:00:00
#3 2010-01-03 08:00:00 2010-01-03 19:00:00
#4 2010-01-04 08:00:00 2010-01-04 19:00:00
#5 2010-01-05 08:00:00 2010-01-05 19:00:00
#6 2010-01-06 08:00:00 2010-01-06 19:00:00
#7 2010-01-07 08:00:00 2010-01-07 19:00:00
#8 2010-01-08 08:00:00 2010-01-08 19:00:00
#9 2010-01-09 08:00:00 2010-01-09 19:00:00
#10 2010-01-10 08:00:00 2010-01-10 19:00:00