我有一个POSIXct变量,其值为"2012-04-15 16:49:36 CEST“。format函数以十进制数返回年份、一年中的周和工作日,在本例中为2012 15 0。对不太熟悉格式的人的说明:
然后,我尝试将值转换回POSIXct变量,然后发生意想不到的事情。当我读取这些值时,函数似乎解释了错误的日期(2012-04-08)。然而,当我使用Sys.time()对第二个示例执行相同的过程时,就会感到惊讶,它的工作方式与预期的一样。有人能解释一下为什么在第一个例子中它不起作用吗?
(TS <- structure(1334501376, class = c("POSIXct", "POSIXt")))
(TS_YWw <- format(TS,format="%Y %W %w"))
as.POSIXct(TS_YWw,format="%Y %W %w")
(TS <- Sys.time())
(TS_YWw <- format(TS,format="%Y %W %w"))
as.POSIXct(TS_YWw,format="%Y %W %w")输出
> (TS <- structure(1334501376, class = c("POSIXct", "POSIXt")))
[1] "2012-04-15 16:49:36 CEST"
> (TS_YWw <- format(TS,format="%Y %W %w"))
[1] "2012 15 0"
> as.POSIXct(TS_YWw,format="%Y %W %w")
[1] "2012-04-08 CEST"
>
> (TS <- Sys.time())
[1] "2013-05-16 15:27:44 CEST"
> (TS_YWw <- format(TS,format="%Y %W %w"))
[1] "2013 19 4"
> as.POSIXct(TS_YWw,format="%Y %W %w")
[1] "2013-05-16 CEST"顺便说一下,我在WindowsXP32bit计算机上运行了R2.15.3的代码。谢谢大家!
发布于 2013-05-16 14:28:44
好像是个虫子。下面我创建了2012年的日子序列(dtimes),并使用'%Y %W %w‘格式将其转换为字符串,然后再转换回来。对这两个系列进行比较,head输出显示在转换中没有保留哪些日期时间。有一个明显的每周模式。还请注意,as.POSIXct('2012 0 0', '%Y %W %w')返回NA。
dtimes <- seq(as.POSIXct('2012-1-1'), as.POSIXct('2013-1-1'), by=as.difftime(1, units='days'))
convert.YWw <- function(dtime) {
fmt <- "%Y %W %w"
string <- format(dtime, format=fmt)
as.POSIXct(string, format=fmt)
}
converted <- lapply(dtimes, convert.YWw)
preserved <- dtimes == converted
dtimes.and.converted <- mapply(function(d, c) c(dtime=d, convert=c), dtimes, converted, SIMPLIFY=FALSE)
head(dtimes.and.converted[! preserved])
# [[1]]
# NULL
#
# [[2]]
# dtime convert
# "2012-01-08 EST" "2012-01-01 EST"
#
# [[3]]
# dtime convert
# "2012-01-15 EST" "2012-01-08 EST"
#
# [[4]]
# dtime convert
# "2012-01-22 EST" "2012-01-15 EST"
#
# [[5]]
# dtime convert
# "2012-01-29 EST" "2012-01-22 EST"
#
# [[6]]
# dtime convert
# "2012-02-05 EST" "2012-01-29 EST" https://stackoverflow.com/questions/16589257
复制相似问题