问题
I am working on building a time series in R programming language. I m having a zoo object which is follows:
I 'd like to convert this into a weekly time series data for analysis and typed in the following code
tt2<-as.ts(zz,freq=365.25/7,start=decimal_date(ymd("2018-01-01")))
tt2[is.na(tt2)]<-0
However, I get the following output:
Time Series:
Start = 17538
End = 18532
Frequency = 0.142857142857143
While I'd like to see the output in line with something like this:
Time Series:
Start = c(2018,2)
End = c(2020,40)
Frequency = 52
or since we can have both 53 and 52 weeks, something like:
Time Series:
Start = 1991.0848733744
End = 2005.34360027378
Frequency = 52.1785714285714
I also tried to do the following ,
library(zoo)
zz <- read.zoo(data, split = 1, index = 2,FUN=as.week")
and converted the following into the format:
However, if i try to convert this into a time series, I receive the following output:
Time Series:
Start = 2505
End = 2647
Frequency = 1
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[40] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[79] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[118] NA NA NA NA NA NA NA NA NA 64 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
I'd be keen to receive your thoughts on this
回答1:
I suppose using tsibble would more easier to convert your series from daily frequency to weekly frequency. At the end you can change to zoo object again.
Here is a short code on what I done
data
# A tibble: 14 x 2
Date Y
<date> <dbl>
1 2020-01-01 0.176
2 2020-01-02 0.521
3 2020-01-03 0.348
4 2020-01-04 0.801
5 2020-01-05 0.963
6 2020-01-06 0.0723
7 2020-01-07 0.638
8 2020-01-08 0.842
9 2020-01-09 0.298
10 2020-01-10 0.902
11 2020-01-11 0.943
12 2020-01-12 0.884
13 2020-01-13 0.266
14 2020-01-14 0.789
library(tsibble)
library(tidyverse)
library(zoo)
data$Date<-as.Date(data$Date)
data.w<-data%>%as_tsibble(index=Date)%>% index_by(year_week = ~ yearweek(.)) %>% summarise(weekly = sum(Y, na.rm = TRUE))
data.z<-zoo(data.w)
> data.z
year_week weekly
1 2020 W01 2.809756
2 2020 W02 4.579329
3 2020 W03 1.055690
来源:https://stackoverflow.com/questions/64960531/converting-zoo-object-into-a-weekly-time-series