2013-04-10 146 views
1

我在7天内测量了数据。部分数据如下所示:每周(7天)将数据汇总到R中的每月

start wk end wk  X1 
2/1/2004 2/7/2004 89 
2/8/2004 2/14/2004 65 
2/15/2004 2/21/2004 64 
2/22/2004 2/28/2004 95 
2/29/2004 3/6/2004 79 
3/7/2004 3/13/2004 79 

我想这一周(7天)的数据转换成使用X1的加权平均月度数据。请注意,7天X1数据中的一些将从一个月重叠到另一个月(在2004年2/29至3/6期间,X1 = 79)。

具体来说,我将获得2004年2月的月度数据(比如,Y1)以下方式

(7*89 + 7*65 + 7*64 + 7*95 + 1*79)/29 = 78.27 

是否R 5具有一个功能,将正确做到这一点? (to.monthly在xts库不做我所需要的)如果,而不是什么是在R中做到这一点的最佳方式?

回答

3

转换数据,以每日数据然后汇总:

Lines <- "start end X1 
2/1/2004 2/7/2004 89 
2/8/2004 2/14/2004 65 
2/15/2004 2/21/2004 64 
2/22/2004 2/28/2004 95 
2/29/2004 3/6/2004 79 
3/7/2004 3/13/2004 79 
" 

library(zoo) 

# read data into data frame DF 
DF <- read.table(text = Lines, header = TRUE) 

# convert date columns to "Date" class 
fmt <- "%m/%d/%Y" 
DF <- transform(DF, start = as.Date(start, fmt), end = as.Date(end, fmt)) 

# convert to daily zoo series 
to.day <- function(i) with(DF, zoo(X1[i], seq(start[i], end[i], "day"))) 
z.day <- do.call(c, lapply(1:nrow(DF), to.day)) 

# aggregate by month 
aggregate(z.day, as.yearmon, mean) 

最后一行给出:

Feb 2004 Mar 2004 
78.27586 79.00000 
+0

是的,完善的需要他们。我试图将数据转换为每日数据,并且无法高效地完成。非常感谢 – 2013-04-10 20:40:28

0

如果你愿意为了让您的DF摆脱“结束一周”的,申请。月会像魅力一样工作。

DF.xts <- xts(DF$X1, order.by=DF$start_wk) 

DF.xts.monthly <- apply.monthly(DF.xts, "sum") 

那么你可以随时重建结束日期,如果你完全加入30