3

当我尝试在我的数据集中本地化“日期”(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。请帮忙!

4

2 回答 2

2

使用 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,它将转换为那个。

于 2012-07-24T17:05:23.683 回答
0

您可以使用内置的时区处理POSIXct

> start_time <- as.POSIXct(date,"%Y-%m-%d %H:%M", tz = "America/New_York")
> start_time
[1] "2011-07-26 07:23:00 EDT" "2011-07-29 07:34:00 EDT" "2011-07-29 07:40:00 EDT"
> format(start_time, tz="Europe/London", usetz=TRUE)
[1] "2011-07-26 12:23:00 BST" "2011-07-29 12:34:00 BST" "2011-07-29 12:40:00 BST"
> format(start_time, tz="Asia/Singapore", usetz=TRUE)
[1] "2011-07-26 19:23:00 SGT" "2011-07-29 19:34:00 SGT" "2011-07-29 19:40:00 SGT"
于 2012-07-24T17:04:53.200 回答