【问题标题】:Summing columns on every nth row of a data frame in R [duplicate]对R中数据框的每n行的列求和[重复]
【发布时间】:2015-02-01 20:19:08
【问题描述】:

我有从动物跑步实验中获得的 12511 行和 16 列的数据框。代表每只动物每分钟跑步计数的每一行。我想对每 60 行的列求和(即每小时计数)。

我尝试使用 apply 函数对 60 行求和:

apply(rw[1:60,],2,sum) 
apply(rw[61:120,],2,sum)
apply(rw[121:180,],2,sum)

... 一直这样做到 12511 是不可想象且耗时的。

我确信有一种聪明的方法可以将我的数据压缩到 208 行。请帮忙!!

谢谢。

【问题讨论】:

  • 12511 不被 60 等分

标签: r sum rows


【解决方案1】:

这是一种使用data.table 包和矢量化colSums函数的方法

一些数据先:

set.seed(123)
rw <- data.frame(a = sample(12511), b = sample(12511), c = sample(12511))

然后,我们将使用gl 创建和索引,并为每个组运行colSums

library(data.table)
setDT(rw)[, as.list(colSums(.SD)), by = gl(ceiling(12511/60), 60, 12511)]
#       gl      a      b      c
#   1:   1 378678 387703 388143
#   2:   2 384532 331275 341092
#   3:   3 355397 367039 369012
#   4:   4 378483 355384 367988
#   5:   5 365193 372779 388020
# ---                         
# 205: 205 385361 409004 389946
# 206: 206 407232 406940 345496
# 207: 207 363253 357317 356878
# 208: 208 387336 383786 348978
# 209: 209 186874 188616 183500

另一种类似的方法是

setDT(rw)[, lapply(.SD, sum), by = gl(ceiling(12511/60), 60, 12511)]

或者使用dplyrs summarise_each函数,也可以这样

library(dplyr)
rw %>%
  group_by(indx = gl(ceiling(12511/60), 60, 12511)) %>%
  summarise_each(funs(sum))
# Source: local data table [209 x 4]
# 
#    indx      a      b      c
# 1     1 378678 387703 388143
# 2     2 384532 331275 341092
# 3     3 355397 367039 369012
# 4     4 378483 355384 367988
# 5     5 365193 372779 388020
# 6     6 387260 386737 347777
# 7     7 343980 412633 383429
# 8     8 355059 352393 336798
# 9     9 372722 386863 425622
# 10   10 406628 370606 362041
# ..  ...    ...    ...    ...

【讨论】:

  • 我喜欢使用gl()ceiling() 生成索引。解决方案处理不相等的组大小。 +1!对于dplyr 方法,我想出了group_by(id = gl(ceiling(nrow(.)/60), 60, nrow(.))),以防他的数据集输入不是总是 12511
  • 非常感谢,我没有注意到@RStudent 的第一个代码忽略了我的一些数据。但是我只是尝试使用您的代码来计算完整的数据,但没有弄清楚输出中的(---)是什么?如何使数据可见:)
  • 将结果保存在某处,然后在其上使用View
  • 我刚开始使用 R 或一般编程:)
  • Res &lt;- setDT(rw)[, as.list(colSums(.SD)) , gl(ceiling(12511/60), 60, 12511)] ; View(Res)
【解决方案2】:

这是我使用 David Arenburg 数据的版本:

set.seed(123)
rw <- data.frame(a = sample(12511), b = sample(12511), c = sample(12511))

ind <- c(rep(60, floor(dim(rw)[1]/60)), floor(dim(rw)[1]%%60))
ind <- rep(1:length(ind), times = ind)
head(apply(rw, 2, function(x) tapply(x, ind, sum)))
       a      b      c
1 378678 387703 388143
2 384532 331275 341092
3 355397 367039 369012
4 378483 355384 367988
5 365193 372779 388020
6 387260 386737 347777

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 2017-02-18
    • 2019-02-04
    • 2019-02-19
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多