gpt4 book ai didi

r - 通过添加到 POSIXlt 来更改不同时区的日期

转载 作者:行者123 更新时间:2023-12-02 02:13:39 24 4
gpt4 key购买 nike

当我尝试在我的数据集中为“date”(class=POSIXlt 的变量)本地化时间时遇到错误。示例代码如下:

# All dates are coded by survey software in EST(not local time)
date <- c("2011-07-26 07:23", "2011-07-29 07:34", "2011-07-29 07:40")
region <-c("USA-EST", "UK", "Singapore")

#Change the times based on time-zone differences
start_time<-strptime(date,"%Y-%m-%d %h:%m")
localtime=as.POSIXlt(start_time)
localtime<-ifelse(region=="UK",start_time+6,start_time)
localtime<-ifelse(region=="Singapore",start_time+12,start_time)

#Then, I need to extract the hour and weekday
weekday<-weekdays(localtime)
hour<-factor(localtime)

我的 “ifelse” 语句一定有问题,因为我收到错误:number of items to replace is not a multiple of replacement length。请帮忙!

最佳答案

使用 R 的原生时间码怎么样?诀窍是您不能在 POSIX 向量中有多个时区,因此请改用列表:

region <- c("EST","Europe/London","Asia/Singapore")
(localtime <- lapply(seq(date),function(x) as.POSIXlt(date[x],tz=region[x])))
[[1]]
[1] "2011-07-26 07:23:00 EST"

[[2]]
[1] "2011-07-29 07:34:00 Europe/London"

[[3]]
[1] "2011-07-29 07:40:00 Asia/Singapore"

并在单个时区转换为矢量:

Reduce("c",localtime)
[1] "2011-07-26 13:23:00 BST" "2011-07-29 07:34:00 BST"
[3] "2011-07-29 00:40:00 BST"

请注意,我的系统时区是 BST,但如果您的系统时区是 EST,它将转换为该时区。

关于r - 通过添加到 POSIXlt 来更改不同时区的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11635265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com