如何避免 "some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique"?

How do I avoid the "some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique"?

我正在尝试找到一种方法,在不触发警告的情况下将列附加到我的动物园对象:

Warning in zoo(rval, index(x)[i]) : some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique

假设我有以下代码:

a <- read.zoo(data.frame(date=as.Date('2011-12-31') + 0:49, col1=seq(1,50), col2=seq(11,60)), FUN = as.Date)
mon <- read.zoo(data.frame(date=c(as.Date('2012-01-01'), as.Date('2012-02-01'), as.Date('2012-03-01')), mc=letters[1:3], mc2=LETTERS[1:3]), FUN = as.Date)

假设我想将 index(mon) 附加到 a 以便我以后可以参考它:

a$month <- as.numeric(index(mon[MATCH(as.yearmon( time(a)), as.yearmon(time(mon)))]))

执行此操作的正确方法是什么,这样我就不会收到警告?

如果我理解正确的话,您需要 a 索引的第一个月的日期的数值,除非 year/month 没有出现在 [=13= 的索引中] 在那种情况下你想要 NA.

mon.ym <- as.yearmon(index(mon))
a$month <- as.numeric(as.Date(mon.ym))[ match(as.yearmon(index(a)), mon.ym) ]

没有 match 的替代方案是:

a.ym <- as.yearmon(index(a))
a$month <- ifelse(a.ym %in% as.yearmon(index(mon)), as.Date(a.ym), NA)