将每月列值汇总为季度值 [英] Aggregating monthly column values into quarterly values
问题描述
大家好,我对R完全陌生,我们将不胜感激。从2004年到2013年,我每个月都有以下数据(称为抑郁症汇总):
月年抑郁量
$ p $我正在尝试创建一个新列,其中包含每个季度(例如2004 Q1、2004 Q2等)每年的汇总值。我尝试使用函数聚合,但未成功。希望你能帮我!问候
1 01 2004 285
2 02 2004 323
3 03 2004 267
4 04 2004 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 2004 273
解决方案1)如果
DF
是输入data.frame,将其转换为带有yearmon
索引的动物园对象z
,然后将其汇总为yearqtr
:库(动物园)
toYearmon <-函数(y,m)as.yearmon(paste(y,m,sep =-))
z <-read.zoo(DF,index = 2:1,FUN = toYearmon)
ag<-合计(z,as.yearqtr,和)
给予:
> ag
2004 Q1 2004 Q2 2004 Q3 2004 Q4
875820785608
2)也可以:
库(动物园)
yq<-as.yearqtr(as.yearmon(paste(DF $ Year,DF $ Month),%Y%m))
ta <-tapply(DF $ DepressionCount,yq,sum)
Hello Everybody I am pretty much completely new to R and any help is greatly appreciated. I have the following data (called "depressionaggregate") from 2004 until 2013 for each month:
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
I am trying to create a new column with the aggregated values for each year for each quarter (i.e. 2004 Q1, 2004 Q2 etc.). I have tried using the function aggregate but have not been successful. Hope you can help me! Regards
解决方案1) If
DF
is the input data.frame convert it to a zoo objectz
with a"yearmon"
index and then aggregate that to"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)
giving:
> ag 2004 Q1 2004 Q2 2004 Q3 2004 Q4 875 820 785 608
2) This would also work:
library(zoo) yq <- as.yearqtr(as.yearmon(paste(DF$Year, DF$Month), "%Y %m")) ta <- tapply(DF$DepressionCount, yq, sum)
这篇关于将每月列值汇总为季度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!