2

我想用一个变量来增加一个动物园对象,我可以用它来测试月份的变化。我确信有更通用的方法可以做到这一点。那里的建议会很好,但我想了解为什么这种简单的方法会失败。如果我了解我在这里缺少的东西,我会感觉更好;-)

例如对于动物园对象

library(zoo)
tz <- structure(c(7L, 7L, 1L, 6L, 0L, 9L, 0L, 1L, 6L, 0L, 3L, 3L, 5L, 
0L, 8L, 2L, 0L, 3L, 2L, 5L, 2L, 3L, 4L, 7L, 8L, 9L, 0L, 1L, 4L, 
5L, 6L, 7L, 8L, 2L, 3L, 4L, 5L, 8L, 9L, 0L), .Dim = c(20L, 2L
), .Dimnames = list(NULL, c("x", "y")), index = structure(c(13880, 
13881, 13913, 13916, 13946, 13947, 13948, 13980, 13983, 13984, 
13985, 14016, 14048, 14082, 14083, 14115, 14147, 14180, 14212, 
14243), class = "Date"), class = "zoo")

使用 as.yearmon() 添加年/月变量似乎很容易。如果我在一个数据框中,这将产生一个很好的字符变量,但是如果你忘记包装 as.numeric() 在动物园里悲剧就会发生

tz$yrmo <- as.numeric(as.yearmon(index(tstz)))
> head(tz)
           x y     yrmo
2008-01-02 7 2 2008.000
2008-01-03 7 3 2008.000
2008-02-04 1 4 2008.083
2008-02-07 6 7 2008.083
2008-03-08 0 8 2008.167
2008-03-09 9 9 2008.167

这看起来很棒,我可以成功比较数据元素

(tz$x[6] != tz$y[6])
2008-03-09
错误

但是为什么当我比较年/月变量时会得到这个结果?

> (tz$yrmo[2] != tz$yrmo[1])
Data:
logical(0)

Index:
character(0)

为什么以这种方式测试 yearmon 或带有 same() 的数据项会失败?(两者都应该是真的)

> identical(tz$yrmo[2] , tz$yrmo[1])
[1] FALSE
> identical(tz$x[2] , tz$x[1])
[1] FALSE

我在使用在动物园中创建索引类的 yearmon() 时只是在玩火吗?我应该改用 Dirk Eddelbuettel 的“把日期变成月份数字”这样的东西吗? 两个日期之间的月数

4

1 回答 1

3

Q1:输出中包含数据和索引部分的线索是这些是动物园对象。因此它们也具有比较的索引属性并且它们不相等。如果你想比较这些值,那么你可以访问 coredata():

> (coredata(tz$yrmo[2]) != coredata(tz$yrmo[1]))
[1] FALSE
> coredata(tz$yrmo[2])
[1] 2008
> coredata(tz$yrmo[1])
[1] 2008

Q2:identical检查的不仅仅是数值。它还确定所有属性的相等性。

> attributes(tz$yrmo[2])
$index
[1] "2008-01-03"

$class
[1] "zoo"
于 2011-09-05T18:58:09.233 回答