我有data.frame
,其中包含两列:
UTCTime
这是UTC区域的活动时间TimeZone
这是发生事件的实际时区我的数据样本:
UTCTime <- as.POSIXct(c("2018-04-12 17:23:14", "2018-04-12 17:17:14","2018-04-12 07:48:20", "2018-04-12 11:25:04", "2018-04-12 11:24:38"), tz = "UTC")
TimeZone <- c("Europe/Prague", "Europe/Dublin", "Europe/Prague", "Europe/Prague", "Europe/Prague")
df <- cbind.data.frame(UTCTime, TimeZone, stringsAsFactors = FALSE)
df
UTCTime TimeZone
1 2018-04-12 17:23:14 Europe/Prague
2 2018-04-12 17:17:14 Europe/Dublin
3 2018-04-12 07:48:20 Europe/Prague
4 2018-04-12 11:25:04 Europe/Prague
5 2018-04-12 11:24:38 Europe/Prague
我想在当地时区获取一个时间向量。我成功地做了一行:
> format(df$UTCTime[1], "%Y-%m-%d %H:%M:%S", tz = df$TimeZone[1])
[1] "2018-04-12 19:23:14"
但是,当我尝试将此应用于整个data.frame
时,我收到错误:
> apply(df, 1, function(x) format(x["UTCTime"], "%Y-%m-%d %H:%M:%S", tz = x["TimeZone"]))
Error in format.default(x["UTCTime"], "%Y-%m-%d %H:%M:%S", tz = x["TimeZone"]) :
invalid 'trim' argument
当我尝试将任何其他功能传递给apply
时,一切都按预期工作:
> apply(df, 1, function(x) paste(x["UTCTime"], x["TimeZone"]))
[1] "2018-04-12 17:23:14 Europe/Prague" "2018-04-12 17:17:14 Europe/Dublin" "2018-04-12 07:48:20 Europe/Prague"
[4] "2018-04-12 11:25:04 Europe/Prague" "2018-04-12 11:24:38 Europe/Prague"
invalid 'trim' argument
?答案 0 :(得分:3)
唯一的问题是允许时区变化。解决方案:
mapply(df$UTCTime, tz = df$TimeZone, FUN = format)
## [1] "2018-04-12 19:23:14" "2018-04-12 18:17:14" "2018-04-12 09:48:20"
## [4] "2018-04-12 13:25:04" "2018-04-12 13:24:38"
答案 1 :(得分:0)
您可以使用tidyverse
:
df %>%
rowwise %>%
transmute(LocalTime = format(UTCTime, tz = TimeZone))
# A tibble: 5 x 1
LocalTime
<chr>
1 2018-04-12 19:23:14
2 2018-04-12 18:17:14
3 2018-04-12 09:48:20
4 2018-04-12 13:25:04
5 2018-04-12 06:24:38