2012-08-16 60 views
1

我有以下格式的一些數據:提取一個月的時間序列意味着R中

date  x  
    2001/06 9949 
    2001/07 8554 
    2001/08 6954 
    2001/09 7568 
    2001/10 11238 
    2001/11 11969 
    ... more rows 

我想提取×平均每月。我嘗試了一些代碼,但 失敗。感謝您爲此提供的任何幫助。

+0

看起來你已經有了它... – GSee 2012-08-16 13:01:05

+0

無數據接着說:2002/01 ... 2012/01,2012/02。 – Fernando 2012-08-16 13:03:14

回答

1

這裏我模擬叫df更多的數據的數據幀:

df <- data.frame( 
     date = apply(expand.grid(2001:2012,1:12),1,paste,collapse="/"), 
     x = rnorm(12^2,1000,1000), 
     stringsAsFactors=FALSE) 

通過移除杉杉四個數字後跟一個斜槓使用您的date載體構建,你可以得到個月的方式。在這裏,我用這個作爲索引變量tapply計算方法:

with(df, tapply(x, gsub("\\d{4}/","",date), mean)) 
+0

很好的解決方案,謝謝! – Fernando 2012-08-16 13:25:15

+0

注意結果是以不同順序命名的向量。名字給了幾個月。 – 2012-08-16 13:26:10

+0

是的,我看到了 - 這個重新排序實際上幫助我! – Fernando 2012-08-17 14:19:46

0

對不起...只是創建一個月份序列矢量然後使用tapply。 這是非常容易的:

m.seq = rep(c(6:12, 1:5), length = nrow(data)) 
m.means = tapply(data$x, m.seq, mean) 

但反正評論的感謝!