对R中数据框的每n行的列求和 [英] Summing columns on every nth row of a data frame in R

查看:41
本文介绍了对R中数据框的每n行的列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have data frame with 12511 rows and 16 columns obtained from animal running experiment. Each row representing running counts every minute for each animal. I would like to sum the columns on every 60th row (that is counts per hour).

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

I tried to use apply function for summing 60 rows:

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

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

... keeping to do this until 12511 is unthinkable and time consuming.

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

I am sure there is a smart way to condense my data to 208 rows. Please help!!

谢谢.

推荐答案

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

Here's an approach using data.table package and the vectorized colSumsfunction

一些数据先:

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

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

Then, we will create and index using gl and run colSums per group

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)]

<小时>

或者使用dplyrsummarise_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
# ..  ...    ...    ...    ...

这篇关于对R中数据框的每n行的列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆