![](/img/trans.png)
[英]R: how to use the aggregate()-function to sum data from one column if another column has a distinct value?
[英]How to aggregate data one after another in r?
假設我有每小時(總共 6 小時)波高數據,如下所示。 我使用mean
function 將它們聚合為 2 小時和 3 小時的高度
h_1<-c(2, 4, 6, 7, 9, 11)
這是我使用的 function:
agg_direct<-function(x){
y<-as.data.frame(x)
names(y)<-c("wh")
agg<-lapply(c(1, 2, 3), function(x)
tapply(y$wh, as.integer(gl(nrow(y), x, nrow(y)) ), FUN = mean))
}
out<-agg_direct(h_1)
輸出:
$h_1
1 2 3 4 5 6
2 4 6 7 9 11
$h_2
1 2 3
3.0 6.5 10.0
$h_3
1 2
4 9
但這正是我想要的:
For 2-h, mean of (2,4), (4,6), (6,7), (7,9), (9,11)
For 3-h, mean of (2,4,6), (4,6,7), (6,7,9), (7,9,11)
所以輸出將是這樣的:
For 2-h: 3, 5, 6.5, 8, 10
For 3-h: 4, 5.66, 7.33, 9
這個過程將在 4 小時、5 小時之后執行……
我們可以使用zoo
的rollmean
library(zoo)
rollmean(h_1, 2)
#[1] 3.0 5.0 6.5 8.0 10.0
rollmean(h_1, 3)
#[1] 4.000000 5.666667 7.333333 9.000000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.