2016-04-28 99 views
1

我有幾個合併的每日動物園時間序列(假設合併集的名稱是「測試」)出現在以下格式:平均時間系列apply.daily(

>test 


       TS1  TS2  TS3 
2014-07-30 2.0  3.0  4.0 
2014-07-31 2.5  3.0  4.5 
2014-08-01 3.0  3.0  5.0 

我想通過幾種方式來聚合/操縱時間序列。然而,最簡單的平均或suming正在逃避我。我試過如下:

ts <- apply.daily(as.xts(test),mean) 

,我原以爲會給我下面的輸出:

>ts 

        X  
    2014-07-30 3.0  
    2014-07-31 3.3  
    2014-08-01 3.7  

但是,它會返回與之前相同的時間序列。我知道這對我計劃使用的apply.weekly()apply.monthly()很有用,但是我怎樣才能適應所有這些功能,在相同的基礎上將TS1,TS2和TS3換成總體平均值,同時保持動物園/ xts格式。基於示例

非常感謝

回答

1

表明,我們可以連接行,並採取mean

apply.daily(as.xts(test), function(x) round(mean(c(x)),1)) 
#   [,1] 
#2014-07-30 3.0 
#2014-07-31 3.3 
#2014-08-01 3.7 

注意,使用的日常數據集的OP代碼返回輸入數據,只有對標準進行單一觀察。假設如果該數據集是DateTime類,然後使用apply.daily將返回mean爲每一天,與另一個mean包起來,以獲得mean的每一行,即

test1 <- structure(list(TS1 = c(2, 2.5, 3, 2.2), TS2 = c(3, 3, 3, 3.2), 
TS3 = c(4, 4.5, 5, 4.4)), .Names = c("TS1", "TS2", "TS3"), 
class = "data.frame", row.names = c("2014-07-30 07:00:00", 
"2014-07-31 05:00:00", "2014-08-01 03:00:00", "2014-07-30 07:20:00")) 

apply.daily(as.xts(test1), function(x) round(mean(mean(x)),1)) 
#     [,1] 
#2014-07-30 07:20:00 3.1 
#2014-07-31 05:00:00 3.3 
#2014-08-01 03:00:00 3.7 

由於我們使用匿名函數,我們不需要兩個mean

apply.daily(as.xts(test1), function(x) round(mean(x),1)) 
#      [,1] 
#2014-07-30 07:20:00 3.1 
#2014-07-31 05:00:00 3.3 
#2014-08-01 03:00:00 3.7 

檢查與OP的做法上述結果

apply.daily(as.xts(test1), mean) 
#     TS1 TS2 TS3 
#2014-07-30 07:20:00 2.1 3.1 4.2 
#2014-07-31 05:00:00 2.5 3.0 4.5 
#2014-08-01 03:00:00 3.0 3.0 5.0 

round(mean(c(2.1, 3.1, 4.2)), 1) 
#[1] 3.1 
round(mean(c(2.5, 3.0, 4.5)), 1) 
#[1] 3.3