来自R POSIXlt的奇数输出

时间:2011-09-12 17:21:23

标签: r

有人可以解释第二个d $年不是1?

> d = as.POSIXlt("1900-01-01")
> d$year
[1] 0
> d$mon = d$mon + 12
> d
[1] "1901-01-01"
> d$year
[1] 0
>

与此形成对比:

> d = as.POSIXlt("1900-01-01")
> d
[1] "1900-01-01"
> d$year
[1] 0
> d$year = d$year + 1
> d
[1] "1901-01-01"
> d$year
[1] 1
>

2 个答案:

答案 0 :(得分:3)

这是因为您正在直接操作列表(POSIXlt对象)的元素。打印时,它被标准化为“真实”日期,但是当访问单个元素时,它们仍然具有非标准化值。

考虑 d< - as.POSIXlt(“1900-01-01”)

dput(d)
d$mon <- d$mon + 12
dput(d)
d <- as.POSIXlt(as.POSIXct(d))
dput(d)

给出了

> d <- as.POSIXlt("1900-01-01")
> dput(d)
structure(list(sec = 0, min = 0L, hour = 0L, mday = 1L, mon = 0L, 
    year = 0L, wday = 1L, yday = 0L, isdst = 0L), .Names = c("sec", 
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst"
), class = c("POSIXlt", "POSIXt"))
> d$mon <- d$mon + 12
> dput(d)
structure(list(sec = 0, min = 0L, hour = 0L, mday = 1L, mon = 12, 
    year = 0L, wday = 1L, yday = 0L, isdst = 0L), .Names = c("sec", 
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst"
), class = c("POSIXlt", "POSIXt"))
> d <- as.POSIXlt(as.POSIXct(d))
> dput(d)
structure(list(sec = 0, min = 0L, hour = 0L, mday = 1L, mon = 0L, 
    year = 1L, wday = 2L, yday = 0L, isdst = 0L), .Names = c("sec", 
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst"
), class = c("POSIXlt", "POSIXt"), tzone = c("", "PST", "PDT"
))

请注意,强制转换为POSIXct并返回POSIXlt将其标准化(年份为1,周一为0)

答案 1 :(得分:2)

POSIXlt个对象是列表。您更改了列表的mon元素。这不会更改列表的year元素。

d <- as.POSIXlt("1900-01-01")
unclass(d)
d$mon <- 12
unclass(d)

如果您希望更改更改任何/所有其他列表元素,请将其转换为POSIXct,然后再转换为POSIXlt

unclass(as.POSIXlt(as.POSIXct(d)))