簡體   English   中英

R中apply.daily()中的平均時間序列合計

[英]Averaging time series in aggregate in apply.daily() in R

我有幾個合並的每日動物園時間序列(假設合並集的名稱為“ test”),其顯示格式如下:

>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

我想以幾種方式匯總/處理時間序列。 但是,最簡單的平均或求和方法使我無法逃脫。 我嘗試了以下方法:

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包裝到同樣的基礎,同時保持zoo / xts格式。

非常感謝

根據顯示的示例,我們可以將行連接起來並取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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM