本文介绍了使用 NA 将时间序列转换为.季度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 NA 的多元 zoo 时间序列,我想将其转换为季度序列.

I have a multivariate zoo time series that contains NAs and I want to convert that to a quarterly series.

df1 <-1:12
df1[df1%%4==0] <- NA
zoo.object  <- zoo(matrix(df1, ncol=2),as.Date("2013-01-01")+(0:5)*35)
colnames(zoo.object) <-c("stock1","stock2")


> zoo.object
           stock1 stock2
2013-01-01      1      7
2013-02-05      2     NA
2013-03-12      3      9
2013-04-16     NA     10
2013-05-21      5     11
2013-06-25      6     NA

理想情况下,我希望保留每只股票的本季度早期数据.我曾尝试从 xts 包中每季度一次,但问题是它删除了带有 NA 的行.

Ideally, I would like to keep the earlier data in the quarter for each stocks.I have tried to.quarterly from the xts package, but the problem is that it removes lines with NAs.

> to.quarterly(zoo.object,OHLC = FALSE)
        stock1 stock2
2013 Q1      3      9
2013 Q2      5     11
Warning message:
In to.period(x, "quarters", indexAt = indexAt, name = name, ...) :
  missing values removed from data

我也考虑过使用 na.locf,但这将数据从一个季度传送到下一个.(在 2013 年 4 月 16 日(第 1 季度)的股票 1 示例中,不应等于 3(因为这是第 2 季度的值).reverse na.locf 也不起作用,因为它可能带有下个季度的数字.

I have also thought about using na.locf, but this carries data from one quarter to the next. (in the example stock 1 on 2013-04-16 (quarter 1) should not be equal to 3 (as this is a quarter 2 value). A reverse na.locf would not work either because it could carry numbers from a later quarter.

以我的例子为例,这是我想要的:

Using my example, here’s what I would like:

        stock1 stock2
2013 Q1      1      7
2013 Q2      5     10

推荐答案

试试这个

library(xts)
(z <- period.apply(zoo.object, endpoints(zoo.object, "quarters"), 
                    function(x) first(na.locf(x, fromLast=TRUE))))
#           stock1 stock2
#2013-03-12      1      7
#2013-06-25      5     10

根据评论,您可以将索引转换为yearqtr:

index(z) <- as.yearqtr(index(z))
z
#         stock1 stock2
#2013 Q1       1      7
#2013 Q2       5     10

或者你更喜欢

index(z) <- as.Date(as.yearqtr(index(z)))
z
#           stock1 stock2
#2013-01-01      1      7
#2013-04-01      5     10

这篇关于使用 NA 将时间序列转换为.季度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 11:20