【发布时间】:2018-12-16 18:22:48
【问题描述】:
我正在尝试关注这个 SO 帖子:Calculate the mean of every 13 rows in data frame,但由于某种原因,它在我这边无法正常工作。他们的例子很好用:
df <- data.frame(a=1:12, b=13:24 );
df
n <- 5;
aggregate(df,list(rep(1:(nrow(df)%/%n+1),each=n,len=nrow(df))),mean)[-1];
a b
1 3.0 15.0
2 8.0 20.0
3 11.5 23.5
但我的,在 dfs 列表上使用 for 循环,并没有:
for (dset in 1:5){
if(dset == 1){n <- 60}
else{n <- 12}#else combine by 12
print(n)
v.ntrade <- aggregate(B.list[[dset]][,7],list(rep(1:(nrow(B.list[[dset]][,7])%/%n+1),each=n,len=nrow(B.list[[dset]][,7]))),sum)
v.volume <- aggregate(B.list[[dset]][,5],list(rep(1:(nrow(B.list[[dset]][,5])%/%n+1),each=n,len=nrow(B.list[[dset]][,5]))),sum)
B.list[[dset]] <- aggregate(B.list[[dset]],list(rep(1:(nrow(B.list[[dset]])%/%n+1),each=n,len=nrow(B.list[[dset]]))),mean)
#replace vol and ntrades
B.list[[dset]][,7] <- v.ntrade[,2]
B.list[[dset]][,5] <- v.volume[,2]
B.list[[dset]] <- B.list[[dset]][,-1] }
之前:
> B.list[[1]][,4]
PAIRclose
1: 8063.21
2: 8065.95
3: 8053.50
4: 8040.00
5: 8054.00
---
75009: 7471.40
75010: 7461.99
75011: 7472.56
75012: 7482.05
75013: 7469.69
之后:
> B.list[[1]][,4]
[1] 5698.0203 2257.8796 2886.9289 1812.9951 1521.3267 2305.9228 1103.6083
等
聚合函数有什么奇怪的行为吗?或者是 %/%n+1 我不知道它是做什么的。
【问题讨论】:
-
您需要提供可重现的数据示例供我们处理。
-
请使用
dput()(不是str或head或图片/屏幕截图)分享您的数据样本,以便其他人可以提供帮助。在此处查看更多信息stackoverflow.com/questions/5963269/…
标签: r time-series aggregate mean