merge.zoo 删除时区 [英] merge.zoo removes time zone
问题描述
merge.zoo
的结果与其输入的时区不同.
The result of merge.zoo
does not have the same time zone as its input.
考虑下面的例子
library(zoo)
zoo_a=zoo(data.frame(a=1:5),
seq(as.POSIXct("2014-01-01 00:00:01",tz="UTC"),
as.POSIXct("2014-01-01 00:00:05",tz="UTC"),
by=1)
)
zoo_b=zoo(data.frame(a=1:4),
seq(as.POSIXct("2014-01-01 00:00:01",tz="UTC"),
as.POSIXct("2014-01-01 00:00:05",tz="UTC"),
by=1)
)
zoo_merged=merge(zoo_a,zoo_b)
time(zoo_merged)[1]
#2013-12-31 19:00:01 EST
time(zoo_a)[1]
#2014-01-01 00:00:01 UTC
time(zoo_b)[1]
#2014-01-01 00:00:01 UTC
与zoo_merged
关联的时区实际上不是EST
而是
The time zone associated with zoo_merged
is not really EST
but
library(lubridate)
tz(time(zoo_merged)[1])
#""
时区属性似乎已被删除,R
可能使用某种默认时区来显示数据.
The time zone attribute seems to have been removed and R
is probably using some sort of default timezone to display the data.
我可以通过lubridate
通过
time(zoo_merged)=with_tz(time(zoo_merged),tz="UTC")
time(zoo_merged)[1]
#2014-01-01 00:00:01 UTC
有什么办法可以正确解决这个问题,即之后不必更改时区?我正在考虑更改 merge.zoo
的代码,但相应代码中没有一行注释......
Is there any way to fix this properly, i.e. without having to change the timezone afterwards?
I was thinking of changing the code for merge.zoo
but there's not a single line of comments in the respective code...
推荐答案
G. Grothendieck 建议的解决方案
Solution as suggested by G. Grothendieck
library(xts)
merge2=function(x,y) {
as.zoo(merge(as.xts(x), as.xts(y)))
}
time(merge2(zoo_a,zoo_b))[1]
#[1] "2014-01-01 00:00:01 UTC"
或者按照 42-
merge3=function(x,y) {
if ((tmp_tzone<-attr(time(x),"tzone"))!=attr(time(y),"tzone")) {
message("Timezone attributes of x and y are not the same. Using default tz.")
return(merge(x,y))
} else {
tmp=merge(x,y)
attr(time(tmp),"tzone")=tmp_tzone
return(tmp)
}
}
#input with same tzones
time(merge3(zoo_a,zoo_b))[1]
#[1] "2014-01-01 00:00:01 UTC"
#input with different tzones
zoo_c=zoo(data.frame(a=1:4),
seq(as.POSIXct("2014-01-01 00:00:01",tz="EDT"),
as.POSIXct("2014-01-01 00:00:05",tz="EDT"),
by=1)
)
time(merge3(zoo_a,zoo_c))[1]
#Timezone attributes of x and y are not the same. Using default tz.
#[1] "2014-01-01 01:00:01 CET"
这篇关于merge.zoo 删除时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!