【发布时间】:2017-02-06 15:45:20
【问题描述】:
我是时间序列分析和使用 xts(和一般的 R)的新手,所以请原谅这个问题的基本性质。
我想按时间范围(例如几个月)和第二个因素变量汇总数据。为了说明我的问题,请参阅以下内容:
require(xts)
# Create example df and convert it to an xts object
date <- sample(seq(as.Date("2015/01/01"), as.Date("2016/12/31"), by="day"),12)
colour <- c("Red", "Red", "Blue", "Blue", "Blue", "Blue", "Red", "Red", "Red",
"Red", "Blue", "Blue")
value <- sample(1:10, 12, replace = TRUE)
df <- cbind.data.frame(date, colour, value)
df <- xts(df[,-1], order.by = df$date)
这将创建一个如下所示的示例数据框:
colour value
2015-01-30 "Blue" "2"
2015-03-15 "Blue" "9"
2015-03-22 "Blue" "9"
2015-08-13 "Blue" "5"
2015-09-01 "Blue" "8"
2015-11-10 "Red" "7"
2016-04-26 "Blue" "2"
2016-07-06 "Red" "9"
2016-07-07 "Red" "6"
2016-07-08 "Red" "2"
2016-10-01 "Red" "6"
2016-11-07 "Red" "2"
我可以使用以下方法总结“价值”变量:
apply.monthly(df$value, FUN = mean)
给我:
value
2015-01-30 2.000000
2015-03-22 9.000000
2015-08-13 5.000000
2015-09-01 8.000000
2015-11-10 7.000000
2016-04-26 2.000000
2016-07-08 5.666667
2016-10-01 6.000000
2016-11-07 2.000000
但我不太明白如何通过(在这种情况下)颜色变量进行聚合(我希望按月计算每种颜色的总和)。任何帮助将不胜感激。
【问题讨论】: