大家好,我对R非常陌生,任何帮助都是非常感谢的。从2004年到2013年,我每个月都有以下数据(称为“抑郁汇总”):
Month Year DepressionCount
1 01 2004 285
2 02 2004 323
3 03 2004 267
4 04 2004 276
5 05 2004 312
6 06 2004 232
7 07 2004 228
8 08 2004 280
9 09 2004 277
10 10 2004 335
11 11 2004 273
我正在尝试创建一个新的列,其中包含每个季度(即2004年Q1、2004年Q2等)的汇总值。我尝试过使用函数聚合,但没有成功。希望你能帮我!问候
发布于 2015-03-05 20:21:52
1) (如果DF
是输入data.frame,则将其转换为带有"yearmon"
索引的动物园对象z
,然后将其聚合到"yearqtr"
library(zoo)
toYearmon <- function(y, m) as.yearmon(paste(y, m, sep = "-"))
z <- read.zoo(DF, index = 2:1, FUN = toYearmon)
ag <- aggregate(z, as.yearqtr, sum)
给予:
> ag
2004 Q1 2004 Q2 2004 Q3 2004 Q4
875 820 785 608
2) --这也适用于:
library(zoo)
yq <- as.yearqtr(as.yearmon(paste(DF$Year, DF$Month), "%Y %m"))
ta <- tapply(DF$DepressionCount, yq, sum)
https://stackoverflow.com/questions/28885939
复制相似问题