在R中合并季度时间序列

时间:2018-09-28 15:13:15

标签: r merge xts

如何合并这样显示的a和b xts系列:

a:

1948-01-01  1

1948-04-01  1

1948-07-01  1

1948-10-01  1

b: 
1948-03-01 2

1948-06-01 2

1948-09-01 2

1948-12-01 2

结果应如下所示

          a   b

1948Q1    1   2

1948Q2    1   2

1948Q3    1   2

1948Q4    1   2

日期的格式无关紧要,只要a和b按四分之一对齐即可。使用indexFormat()和%b%Y等每月更容易做到这一点,但是没有季度可用的索引。

aggregate(a,as.yearqtr)的效果不太好,因为出于某种原因,它把Q​​2作为一年的第一季度。然后,如果要采用年平均值,则每年需要Q2,Q3,Q4,Q1,而不是Q1-Q4。因此,我正在寻找另一种方法。让我知道是否存在。

1 个答案:

答案 0 :(得分:1)

尝试以下两步解决方案:

# Step 1: set rownames as quarters
library(zoo) 
rownames(a) <- format.yearqtr(as.Date(a$V1))
rownames(b) <- format.yearqtr(as.Date(b$V1))
# Step2: merge by rownames (quarters)
merge(a, b, by = "row.names", all = TRUE, suffixes = c(".a",".b"))[, -c(2, 4)]
# output (you can now store the result in a dataframe and change colnames as you want)
  Row.names V2.a V2.b
1   1948 Q1    1    2
2   1948 Q2    1    2
3   1948 Q3    1    2
4   1948 Q4    1    2

数据

a <- structure(list(V1 = c("1948-01-01", "1948-04-01", "1948-07-01", 
"1948-10-01"), V2 = c(1L, 1L, 1L, 1L)), .Names = c("V1", "V2"
), class = "data.frame", row.names = c("1948 Q1", "1948 Q2", 
"1948 Q3", "1948 Q4"))
b <- structure(list(V1 = c("1948-03-01", "1948-06-01", "1948-09-01", 
"1948-12-01"), V2 = c(2L, 2L, 2L, 2L)), .Names = c("V1", "V2"
), class = "data.frame", row.names = c("1948 Q1", "1948 Q2", 
"1948 Q3", "1948 Q4"))