![](/img/trans.png)
[英]Split time series data based on months or quarters for comparing mean and variance values
[英]Differences of values based on mean months and rolling data
我正在嘗試做一些看起來很簡單的事情但是證明有點挑戰,所以我希望有人可以提供幫助!
我有一系列溫度觀察時間:
Lines <-"1971-01-17 298.9197
1971-01-17 298.9197
1971-02-16 299.0429
1971-03-17 299.0753
1971-04-17 299.3250
1971-05-17 299.5606
1971-06-17 299.2380
2010-07-14 298.7876
2010-08-14 298.5529
2010-09-14 298.3642
2010-10-14 297.8739
2010-11-14 297.7455
2010-12-14 297.4790"
DF <- read.table(textConnection(Lines), col.names = c("Date", "Value"))
DF$Date <- as.Date(DF$Date)
mean.ts <- aggregate(DF["Value"], format(DF["Date"], "%m"), mean)
這會產生:
> mean.ts
Date Value
1 01 1.251667
2 02 1.263333
這只是一個例子 - 我的數據是多年的,所以我可以計算出每月的完整數據平均值。
我當時想要做的是計算所有1月份(單獨)的差異與我上面計算的1月份的平均值。
如果我不再使用日期/時間類,我可以用一些循環來做這個但我想知道在R中是否有一個“整潔”的方法來做到這一點? 有任何想法嗎?
您只需將年份添加為聚合變量即可。 使用公式界面更容易:
> aggregate(Value~format(Date,"%m")+format(Date,"%Y"),data=DF,mean)
format(Date, "%m") format(Date, "%Y") Value
1 01 1971 298.9197
2 02 1971 299.0429
3 03 1971 299.0753
4 04 1971 299.3250
5 05 1971 299.5606
6 06 1971 299.2380
7 07 2010 298.7876
8 08 2010 298.5529
9 09 2010 298.3642
10 10 2010 297.8739
11 11 2010 297.7455
12 12 2010 297.4790
至少我理解你的問題,你想要每個月的差異與那些月份的平均值,所以你可能想要使用ave
而不是聚合:
diff.mean.ts <- ave(DF[["Value"]],
list(format(DF[["Date"]], "%m")), FUN=function(x) x-mean(x) )
如果您想在同一個數據框中使用它,那么只需將其指定為一列:
DF$ diff.mean.ts <- diff.mean.ts
ave
函數用於向現有數據幀添加列,因為它返回的長度與第一個參數中的值數相同,在本例中為DF [[“Value”]]。 在當前實例中,它返回所有0,這是正確的答案,因為每個月只有一個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.