【问题标题】:Finding mean of every x observations for list of dataframes查找数据框列表的每个 x 观测值的平均值
【发布时间】: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()(不是strhead或图片/屏幕截图)分享您的数据样本,以便其他人可以提供帮助。在此处查看更多信息stackoverflow.com/questions/5963269/…

标签: r time-series aggregate mean


【解决方案1】:

我们可以通过tidyverse 做到这一点。使用map 循环遍历数据集的list,使用gl 创建分组变量并使用summarise_all 获取所有其他列的mean

library(tidyverse)
lst %>% 
    map(~ .x %>%
            group_by(grp = as.integer(gl(n(), n, n()))) %>% 
            summarise_all(mean))
#[[1]]
# A tibble: 3 x 3
#    grp     a     b
#  <int> <dbl> <dbl>
#1     1   3    15  
#2     2   8    20  
#3     3  11.5  23.5

#[[2]]
# A tibble: 3 x 3
#    grp     a     b
#  <int> <dbl> <dbl>
#1     1   3    15  
#2     2   8    20  
#3     3  11.5  23.5

或将base Rlapplyaggregate 一起使用

lapply(lst, function(x) aggregate(.~ cbind(grp = as.integer(gl(nrow(x),
          n, nrow(x)))), x, mean)[-1])

数据

lst <- list(df, df)

【讨论】:

    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 2013-02-11
    • 2021-06-28
    • 1970-01-01
    • 2021-12-22
    • 2012-02-20
    相关资源
    最近更新 更多